Search⌘ K

Polymorphism in Action

Explore how polymorphism enables Java programs to call subclass methods through superclass references, enhancing code flexibility and reuse. Understand three key cases of polymorphism with practical Java examples to build a solid foundation in object-oriented programming concepts.

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.

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 ...