Home > Tutorial > Java Polymorphism Explained

Java Polymorphism Explained

If your new to Java, you have probably heard the term Polymorphism, but may not understand what it means other than the obvious that it is related to Java. Fair enough, but I am hoping to enlighten you on the subject.

If you had a biology class back in high school, it is likely you were introduced to the term Polymorphism in a textbook. The term Polymorphism in biology refers to the concept of an organism or species that can have many different forms.

Shockingly, this same concept can be applied to Object Oriented Programming like C++, which is a bit old school at this point, or to Java, which may be the coolest programming language in my opinion.


Polymorphism Example

Let’s demonstrate Polymorphism in Java by creating a Widget class and then extend that class to the RoundWidget subclass. We add a an additional field to RoundWidget class for color to show how this all works. The printWidgetDetails() method has been overridden in this example. The RoundWidget subclass overrides this method and prints details that are specific to the subclass.

package com.jcd.java.tutorials.MavenProject;

public class JavaPolymorphism 
{

	public static void main(String[] args) 
	{
		Widget widget1 = new Widget("SQUARE");
		widget1.printWidgetDetails();
		
		Widget widget2 = new RoundWidget("ROUND", "BLUE");
		widget2.printWidgetDetails();
	}

}

class Widget 
{
	private String myType;
	
	public Widget(String type)
	{
		myType = type;
	}
	
	public void printWidgetDetails() 
	{
		System.out.println("This is my basic widget which is "+myType);
	}

}

class RoundWidget extends Widget
{
	private String myColor;
	
	public RoundWidget(String type, String color)
	{
		super(type);
		myColor = color;

	}
	
	public void printWidgetDetails() 
	{
		super.printWidgetDetails();
		System.out.println("This is my round widget that is "+myColor);
	}
	
}
This is my basic widget which is SQUARE

This is my basic widget which is ROUND
This is my round widget that is BLUE


Concluding Comments

You can see Polymorphism in Java with overloading of constructors and methods as well as in the class and subclass inheritance. There is a good read with examples on Java Method Overloading Examples that was published earlier by Smedley. Polymorphism is all about forms.

Seymour
Posted by

Seymour

I have been a software developer for twenty years now focusing on writing high quality Java applications. If you are in a programming field, you know that technology is constantly changing. You have to keep current or you will get left behind!

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

Copyright © 2018 JavaCodeDepot