In the below code , why b1.subtract() fails . Please explain me the reason ie., what happens in JVM while invoking that method .
class Base {
public void add() {
System.out.println("Base ADD");
}
}
class Child extends Base {
public void add(){
System.out.println("Child ADD");
}
public void subtract() {
System.out.println("Child Subtract");
}
}
class MainClass {
public static void main(String args[]) {
Base b1 = new Base();
Base b2 = new Child();
Child b3 = new Child();
b1.add();
b2.subtract(); // ?????????**previously it was b1.subtract and its wrong
b2.add();
b3.subtract();
}
}
I assume, judging by the title, that the code was in fact meant to be
b2.subtract(). Going with that:While b2 is currently an instance of Child, and it is quite easy to see that in your code it will always be an instance of Child, Java is statically typed and so can’t allow you to use the methods of the actual class, just the declared class.
Consider this example:
Now it’s impossible to tell at compile time what b2 will actually be an instance of, so you obviously can’t possibly call any methods in Child (as b2 may just be a plain Base!). It wouldn’t really make sense for there to be an exception to this for cases like your example, as it would cause a lot of confusion and these cases can be easily corrected to work properly as-is (by changing the declared type to Child not Base).