The basic concept in play here is inheritance. A good place to start reading about it is https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
Your example is reversed — it should be
Animal animal = new Cat();
This is because the Cat
class would be a specific kind of Animal
— having everything needed to make an Animal
object, plus some extras.
In code, this could look something like:
public class Test
{
public static class Animal
{
protected String sound;
public String getSound() { return sound; }
public Animal() { sound = ""; }
}
public static class Cat extends Animal
{
public Cat() { super(); sound = "meow"; }
}
public static void main(String[] args) {
Animal animal = new Cat();
System.out.println(animal.getSound());
}
}
And the result would be
meow
because the Cat object has the getSound()
method from the parent Animal, but was created with its own constructor and set the data appropriately.