Reputation: 4940
Look at the code below :
class Marsupial {
public static boolean isBiped() {
return false;
}
public void getMarsupialDescription() {
System.out.println("Value of this : " + this.getClass().getName() + " , Marsupial walks on two legs: " + isBiped());
}
}
public class Kangaroo extends Marsupial {
public static boolean isBiped() {
return true;
}
public void getKangarooDescription() {
System.out.println("Value of this : " + this.getClass().getName() + ", Kangaroo hops on two legs: " + isBiped());
}
public static void main(String[] args) {
Kangaroo joey = new Kangaroo();
joey.getMarsupialDescription(); // Question here
joey.getKangarooDescription();
}
}
The output is :
Value of this : Kangaroo , Marsupial walks on two legs: false
Value of this : Kangaroo, Kangaroo hops on two legs: true
Now why in the call of getMarsupialDescription(), it will choose static method of Marsupial and not of Kangaroo especially when this
points to Kangaroo
?
Upvotes: 1
Views: 92
Reputation: 4940
To put simply association of method call to the method body is type of binding. [What is binding ?] There are two types of binding: Static Binding that happens at compile time and Dynamic Binding that happens at runtime.
Static Binding or Early Binding
The binding which can be resolved at compile time by compiler is known as static or early binding. The binding of static, private and final methods is compile-time. Why? The reason is that the these method cannot be overridden and the type of the class is determined at the compile time. Lets see an example to understand this:
class Human{
public static void walk()
{
System.out.println("Human walks");
}
}
class Boy extends Human{
public static void walk(){
System.out.println("Boy walks");
}
public static void main( String args[]) {
/* Reference is of Human type and object is
* Boy type
*/
Human obj = new Boy();
/* Reference is of HUman type and object is
* of Human type.
*/
Human obj2 = new Human();
// At compile time it gets decided which body of method it will call
obj.walk();
obj2.walk();
}
}
Why at compile time ? As it is static. Static binding is done by Type of reference not by the type of object.
Output:
Human walks
Human walks
Similarly in the code in question above - isBiped() static method is linked to the body of the method during compile time only. Hence it calls Marsupial isBiped().
What is static and dynamic binding ?
Upvotes: 1