object a2 is of type A but references an object of class C. So, a2 should be able to access m3(). But, why is it not happening? If m3() method had been defined in class A, t
Compiler checks reference of object which is invoking a method...
In your case A a2=...
is what compiler can see, and it finds that there is no m3()
method defined in A
class. Hence code will not compile.
Note that, While invoking method at runtime, JVM refers the object referenced by the Reference. In your case Reference of class A is referring Object of class C.
Read more at : Polymorphism in Java