What is the difference between compile-time and runtime polymorphism in Java?
Compile-time polymorphism is resolved when the compiler reads the code, and it is the method overloading. Runtime polymorphism is resolved when the program runs, and it is the method overriding.
public class Main {
public static void main(String[] args) {
System.out.println(pick(1));
System.out.println(pick(1.5));
}
static String pick(int value) {
return "int";
}
static String pick(double value) {
return "double";
}
}
So how do you tell them apart? Here is the table.
the thing compile time run time
------------------- ------------------------ -------------------------
the name overloading overriding
what decides it the types of the the object that the
arguments variable holds
when it is decided when the code is compiled when the line runs
the parent is not involved the parent has the
involved same method
And here is the runtime version, so you can see the difference.
public class Animal {
public String speak() {
return "animal";
}
}
public class Dog extends Animal {
@Override
public String speak() {
return "dog";
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Dog();
System.out.println(a.speak()); // dog, because the object
// is really a Dog
}
}
And there is a useful test for telling them apart in code. If the method is in the same class then it is overloading. If the method is in a child class and the parent has the same one then it is overriding.
the code the answer
------------------------------------------ -------------------------
two methods with the same name in one class overloading
a method in a child with the same name overriding
a static method in a child with the hiding
same name
And the practical difference that matters most is this. With overloading the compiler decides and there is no cost at runtime. With overriding the runtime has to look at the object and work out which method to run, so there is a small cost every time the method is called.
So the rule to remember is this. Overloading is decided by the types of the arguments, and overriding is decided by the object.
The last question in this topic is about why people use the older names.