I have written below example of polymorphism.
package tsys;
public class DynamicPolymorphism {
public void eat(){
System.out.println("DynamicPolymorphism");
}
}
class AnotherClass extends DynamicPolymorphism{
public void eat(){
System.out.println("Another Class");
}
public void consume(){
System.out.println("consume");
}
}
class TestPolymorphism{
public static void main(String args[]){
DynamicPolymorphism dp = new AnotherClass();
dp.eat();//Works fine
dp.consume();//compile time error
}
}
Now question is why compiler complains about dp.consume()
? This question was asked to me in an interview I explained the reason as
"At compile time compiler only knows about Type of reference as type of dp
is DynamicPolymorphism
hence compiler is unable to find the consume
method."
Interviewer counter my answer and asked what happens behind the scenes that compiler gives the error however we are referring variable dp
to an instance of AnotherClass
.
What else I can explains the interviewer against the counter question?