The tricky part of Java method overriding
You can easily override a method of a super class in one of its subclasses. But if you invoke an overridden method from a polymorphic object, the method of the actual object type gets invoked. Let’s look at an example,
class A{
public void test(){
System.out.println(“I’m A”);
}
}
class B{
public void test(){
System.out.println(“I’m B”);
}
}
Then some where in the code you might have a code similar to following
A a=new B();
a.test();
The output would be, I’m B. this is OK. But what happens when you invoke methods which can be overridden by a subclass. Well, let’s see,
class A{
private int a;
public A(int a){
this.a=a;
test();
}
Public void test(){
System.out.println(“value of instance var of A after adding 2=”+(a+2));
}
}
class B{
private int b;
public B(int b){
super(b);
this.b=b;
}
public void test(){
System.out.println((“value of instance var of B after adding 2=”+(b+2));
}
}
Then some where in the code you execute some thing similar to following
B b=new B(1);
The output would be,
value of instance var of B after adding 2=2
The overridden method of class B get called before the instance variable of B is not initialized. Call to super constructor must come first in the constructor of subclass disallowing subclass to initialize variables to avoid this havoc.
This shows that calling methods inside a constructor which can be overridden by subclasses is not suitable. You have to pay the price for it some day. Invoke only those which cannot be overridden by subclasses inside your constructor.