Hello, dear Javarashites. Surely everyone who was interviewed was asked a question about polymorphism. So, I am interested in your answer and the assessment of your answer from the interviewer. I had 2 mini-interviews where they asked about polymorphism and at each of them the interviewer was not happy with my answer. In short, my answer boiled down to overriding and assigning a parent class reference to an object of a child class. Something like this:
class Parent{
void saySomething(){
System.out.println("Parent!");
}
}
class Child1 extends Parent{
@Override
void saySomething(){
System.out.println("Child1!");
}
}
class Child2 extends Parent{
@Override
void saySomething(){
System.out.println("Child2!");
}
}
class Test{
public static void main(String[] args){
Parent p1 = new Parent();
Parent p2 = new Child1();
Parent p3 = new Child2();
p1.saySomething();
p2.saySomething();
p3.saySomething();
}
}
---------------
Output:
Parent!
Child1!
Child2!
This is exactly what is written on the Oracle website. Ivan Golovach says that polymorphism in Java is implemented using inheritance (what I showed in the example) and using generics. So, where is the truth and how to answer at an interview? I have an important interview coming up soon and I don’t want to screw up again on this seemingly basic question.
GO TO FULL VERSION