Why I cannot access Child Object method with Parent Type

后端 未结 5 1033
迷失自我
迷失自我 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:41

    You see the subclass C as an instance of A because an A does not have the function m3 that a C has.

      A a2 = new C();
    

    So here, you can access only the methods in C that are inherited from A. You basically see it as an A. If you wanted to call the methods in C, you would have to cast it to C, so you'd have to do something like this:

     if(a2 instanceof C)
     {
         C castedA2 = (C)a2;
         castedA2.m3();
     }
    

提交回复
热议问题