Polymorphism in Action

Understand the relationship between a superclass and a subclass.

References using inheritance hierarchies

Superclass referenced as the superclass

The first case is pretty simple. When we instantiate a superclass object and store it in a variable of the superclass’s type, Java will call the method of the superclass.

Look at the code below.

Press + to interact
Animal.java
Dog.java
TestDriver.java
public class TestDriver
{
public static void main(String args[])
{
Animal obj = new Animal(4, "brown"); // Creating a dog
// Calling the functions
obj.eat();
obj.sleep();
}
}

Look at line 5 in the TestDriver.java ...