I have two situations drawn up, and the strange differences between them are causing me a bit of grief. I will attempt to detail them below in code.
Situation 1:
public void doSomething(Object obj) {
//do something with obj
}
public void doSomething(String str) {
//do something similar to str, but apply some custom
//processing for String's
}
Object o = new String("s");
doSomething(o); // this will use the Object version...
Situation 2:
class Dog {
void makeSound() {
System.out.println("woof");
}
}
class Chihuahua extends Dog {
void makeSound() {
System.out.println("yip");
}
}
Dog dog = new Chihuahua();
dog.makeSound(); //will print 'yip', the Chihuahua version...
Why, in situation one, is the runtime type of the parameter not used, but in situation two it is? I understand that the examples are actually different things, but I am more curious about what is going on 'under the covers' here.
In the first example, a method signature is chosen at compile-time from among a number of overloaded signatures. The Java language specification says that this is done based on the static type of the variables.
In the second example, an implementation of a given method signature is chosen at runtime based on virtual method dispatch. This is done based on the runtime type of the class containing the method definition.
Situation #1 is method overloading, which is static at compile time. Situation #2 is polymorphism, which is dynamic at runtime.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With