Why I cannot access Child Object method with Parent Type

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

    When you write this line

     A a2=new C();
    

    a2 will only ever be able to access methods defined in Class A.

    Even though a2 refers to an instance of Class C, it cannot invoke methods defined only in C.

    However, if you had the following:

    class A {
        void m3() {
            System.out.println("in A");
        }
    }
    
    class C extends A {
        void m3() {
            System.out.println("in C");
        }
    }
    
    ...
    A a2 = new C();
    a2.m3();
    

    would output

    in C

    In this case, the m3() method is being overridden and the method invoked will be determined by the type of the instance which a2 refers to (i.e. C).

    I would take a look at the Java tutorials here: http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html

    0 讨论(0)
  • 2020-12-07 06:35
    A a2=new C();
    

    That means you can access only the members of Class A and implementations of Class C, if any overridden.

    Now m3 is not a member of A. Clear ?

    0 讨论(0)
  • 2020-12-07 06:39

    If you use a reference of the parent / superclass and try to invoke a method on the subclass, then that method should be defined in the parent / superclass. i.e, what methods you can call on the object(rhs) depends on the lhs (reference type).

    0 讨论(0)
  • 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();
     }
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题