Polymorphism


Some GUI classes traced back
to Object. Class heirarchy
diagram. Used in one of
the GUI projects.

Polymorphism is a very important component of Java’s object orientation is the ability for polymorphism. Polymorphism is just when a class can have more than one is-a relationship. Consider the following two classes:


public class A {
	/* implementation not shown */
}
		


public class B extends A {
	/* implementation not shown */
}
		

We can say that class B is polymorphic as class B is-a A and class B is-an Object. If we look at the included image we can say that JFrame is polymorphic because JFrame is-a Frame, and JFrame is-a Window, and JFrame is-a Container, and JFrame is-a Component, and JFrame is-an Object. Polymorphism is used primarily in conjunction with class casting to specify which class you want an instance to behave as.


Class Casting

In Java classes can be cast just like any other primitive data type. In the same way that int can be implicitly cast to a double, a subclass can be implicitly cast to a superclass. Consider the following perfectly valid statement:


A x = new B();
		

Let’s say that class B had a toString() method. If we call toString() on x as it is, Object’s toString() method will be called since x is currently acting as an A class. If we want to call B’s toString() method we could say something like:


((B)x).toString()
		

Uses Of Polymorphism

As mentioned in a previous tutorial, polymorphism allows the user to refer to an interface rather than an implementation of the interface. If we have a method that only requires the use of the methods declared in one interface, then it is easier to just take the interface as a parameter rather than to have an overload for each class that implements the interface. This same idea applies to super classes and abstract classes. In this way we can reuse even more code, and we don’t have to copy paste as much.