I’m playing with inheritance to try and fully understand it:
I’ve created a parent class with a private method and overridden it in the child class and made it public. I have also overriden the toString method differently for each class. Looks like this:
public class testparent {
public String toString(){
return ("One and two boobaloo");
}
private void hitMe(){
System.out.println("BAM");
}
}
public class testbaby extends testparent{
public String toString() {
return "Bananas";
}
public void hitMe(){
System.out.println("BAMBAM");
}
public static void main(String[] args){
testbaby testy = new testbaby();
testparent test2 = testy;
System.out.println(test2);
//test2.hitMe(); //????? not allowed
System.out.println(testy);
testy.hitMe();
}
}
Now, why is it that printing both objects produces “Bananas”, but I can’t use both classes’ hitMe() methods?
This because of dynamic binding of methods and static typing of the language itself.
What happens is that Java is statically typed AND has dynamic binding, so:
hitMecan be called only ontestbabydeclared variables because it’s private intestparentand, because of static typing, Java must ensure that method can be surely called at runtimetoStringcan be called on both objects (since it’s even inherited fromObject) and which one will be effectively called at runtime it’s chosen according to the runtime instance and NOT according to the variable declaration (because of dynamic binding)According to dynamic binding methodology, the correct and runtime implementation of a method is chosen at run time according to the real instance of the object, not on the declared one.
This means that, even if you declare
test2as atestparent, it is still atestbabyobject (since you are assigning to it atestbabyinstance). At runtime the correct implementation will be the one of the child.This is perfectly legal though, because a
testbabyis atestparent.