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 ?
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 inClass A
, it is only defined inclass B
so, using a reference ofA
, you can't callm2()
Because the reference is of type
A
. The compiler can only enforce calling the methods from this type.