This is a key feature of polymorphism.
The object you instantiated is an instance of Child
. Calling that object's test()
is always going to result in the Child
's (overridden) test()
being called, even if you've assigned that instance to a variable of Parent
type.
In short, this is how you can achieve more specific behavior while only having to reference the object using a variable declared a superclass type. Often this is used in conjunction with the base class only providing an abstract method for the subclasses to override.
A trivial example in beginner's books usually involves animals or cars:
public abstract class Animal
{
private final String name;
public Animal(String name)
{
this.name = name;
}
public void printName()
{
System.out.println(name);
}
// more animal general stuff followed by:
public abstract void makeSound();
}
public class Dog extends Animal
{
public Dog()
{
super("Dog");
}
@Override
public void makeSound()
{
System.out.println("Woof!");
}
}
List<Animal> aList = new ArrayList<Animal>();
aList.add(new Dog());
aList.add(new Cat());
// etc
for (Animal a : aList)
{
a.printName();
a.makeSound(); // calls each subclasses' "makeSound()"
}
You can't call the Parent
's test()
unless you instantiate a Parent
or call super.test()
from within a method in Child
.
(I was actually thinking I could find a good duplicate for this that provided a decent answer, but I couldn't)