Barking Up a Different Tree: A Brief Explanation of Polymorphism
Polymorphism is a concept that appears in object-oriented programming languages. It allows for methods to take on multiple levels of functionality depending on how they are utilized.
Polymorphism in Java is most often exemplified when one class inherits a method from a superclass or parent class.
Let’s take a look at how this operates using a parent class Dog
and three classes of dog breeds that will inherit from Dog
.
class Dog {
public void bark() {
System.out.println(“Doggie says bark!”)
}
}
We can utilize the keyword extends
to allow for one class to inherit the methods of another.
class Bulldog extends Dog {
}
Calling the bark()
method for a Bulldog
without any additional specifications should give us the same result, because the Bulldog
class will inherit the bark()
method from the Dog
class.
Dog myDog = new Dog();
Dog myBulldog = new Bulldog();myDog.bark();
myBulldog.bark();//=> Doggie says bark!
//=> Doggie says bark!
What could we do though with different breeds of dogs whose shouts don’t maybe sound quite like a normal bark? We could utilize the concept of polymorphism, which allows us to take a method as it exists in a parent class and modify its functionality.
class Poodle extends Dog {
public void bark() {
System.out.println(“Poodle says yip!”)
}
}class GreatDane extends Dog {
public void bark() {
System.out.println(“Great Dane says WOOF!”)
}
}Dog myDog = new Dog();
Dog myBulldog = new Bulldog();
Dog myPoodle = new Poodle();
Dog myGreatDane = new GreatDane();myDog.bark();
myBulldog.bark();
myPoodle.bark();
myGreatDane.bark();//=> Doggie says bark!
//=> Doggie says bark!
//=> Poodle says yip!
//=> Great Dane says WOOF!
Notice how the concept of polymorphism is illustrated above.
All four of the variables we assigned were of class Dog
, though the last three were also of a child class of Dog
(Bulldog
, Poodle
, and GreatDane
respectively). This means that all four variables have access to the method bark()
, but the functionality of bark()
morphs depending on which class is utilizing it.
Happy coding!