Dynamic Method invocation (Objects and reference i

2019-08-29 02:32发布

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 ? 

2条回答
何必那么认真
2楼-- · 2019-08-29 03:05
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()

查看更多
何必那么认真
3楼-- · 2019-08-29 03:17

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.

查看更多
登录 后发表回答