Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java -- Runtime typing differences

Tags:

java

runtime

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.

like image 311
nicholas.hauschild Avatar asked May 14 '11 00:05

nicholas.hauschild


2 Answers

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.

like image 173
Mike Samuel Avatar answered Oct 20 '22 16:10

Mike Samuel


Situation #1 is method overloading, which is static at compile time. Situation #2 is polymorphism, which is dynamic at runtime.

like image 25
Brett Kail Avatar answered Oct 20 '22 17:10

Brett Kail