Why I cannot access Child Object method with Parent Type

后端 未结 5 1027
迷失自我
迷失自我 2020-12-07 06:08

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

5条回答
  •  温柔的废话
    2020-12-07 06:43

    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

提交回复
热议问题