according to cathy sierra and bert bates - author of a famous
java book.
"the reference variables type determines the method that can be invoked on the object the variable is referencing."
class Base{
void display(){
System.out.print("Base Class");
}
}
class Sub extends Base{
}
class test{
public static void main(
String a[]){
Base b = new Sub();
considering the above example , it means
b.display() would call the inherited method display() on the object sub because type of reference variable b will decide which method will be called. there is an exception to this rule when there is an overriding method in the subclass. to change the above example accordingly
class Base{
void display(){
System.out.print("Base Class");
}
}
class Sub extends Base{
void display(){
System.out.print("Sub Class");
}
}
class test{
public static void main(String a[]){
Base b = new Sub();
now when there is an overriding method a call to b.display() would result in an actual call to overriden method, in other words now the selection of method depends on the object the reference variable is pointing to, rather than the type of the reference variable.
now see how this rule is flouted
class Base{
void display(){
System.out.print("Base Class");
}
}
class Sub1 extends Base{
void display(){
System.out.print("Sub1 Class");
}
}
class Sub2 extends Sub1{
void display(){
System.out.print("Sub2 Class");
}
}
class Sub3 extends Sub2{
}
class test{
public static void main(String a[]){
Base b = new Sub3();
b.display();
Base class has 1 display() method, Sub1 class has two display methods one inherited and the other is overridding, Sub2 has three - two inherited and one overridding. now sub three will have three display methods - all inherited from above classes. because there is no overriding method in the Sub3 class, the type of reference variable must decide which method to be called. but the result turns out very unexpected .
the output is
Sub2 Class
why this anamolous result???