-4

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?

Sumit Kamboj
  • 846
  • 2
  • 10
  • 17
  • 1
    Downvoters, can you explain what is wrong with question so that I can improve? – Sumit Kamboj Jul 10 '17 at 05:37
  • 1
    I would have asked for clarification, because I don't understand the counter question. There is no "behind the scenes". The compiler knows that `dp` is a `DynamicPolymorphism`, so it will only allow calls it knows about, i.e. calls to methods declared by `DynamicPolymorphism`. Basically what you said. That is the fundamental nature of a [statically-typed](https://stackoverflow.com/q/1517582/5221149) language like Java. – Andreas Jul 10 '17 at 05:42
  • @Andreas Your answer is apt, I am just looking here, Is there something that I missed regarding polymorphism. Thanks – Sumit Kamboj Jul 10 '17 at 05:56

1 Answers1

-2

dp is declared DynamicPolymorphism. hence doesn't know anything about the methods of AnotherClass. If you want to call consume then you need to typecast and call consume. try ((AnotherClass)dp).cosume()

PrashanthBC
  • 275
  • 1
  • 10