Dynamic Method invocation (Objects and reference in inheritance )

天大地大妈咪最大 提交于 2019-12-25 16:47:15

问题


Suppose I have 2 classes ........A Class is base class and class B is derived class and if i create a reference such as : A a=new B(); does it mean that reference a points to object of B Class ? If yes than how am i able to call overridden methods of A in B and not other methods of B ? thank you in advance

class A {
    m1() {
    }
}

class B extends A {
    m1() {
    }

    m2() {
    }
}


 A a=new B();
 a.m1(); //it will call overridden m1() in B 
 a.m2(); //it doesnt work if reference "a" points to object of B than why doesnt it call         m2 method ? 

回答1:


Animal a=new Dog(); // Animal is parent - class, Dog is a child

means, you have an animal reference pointing to a Dog Object. So, only the methods which are declared in the parent class (Animal) can be called using a parent- class reference.

In your case, m2() is not defined in Class A, it is only defined in class B so, using a reference of A, you can't call m2()




回答2:


If yes than how am i able to call overridden methods of A in B and not other methods of B

Because the reference is of type A. The compiler can only enforce calling the methods from this type.



来源:https://stackoverflow.com/questions/25468867/dynamic-method-invocation-objects-and-reference-in-inheritance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!