Polymorphism is the idea of an object being able to “look” or “act” like other types of objects. Now you might wonder why an object should “look” like another type of object, or even how it can look like another object.
Polymorphism exists when you have is-a style relationships. So if you have a class called Fish(), which extends Animal() and implements Swimmer(), then an object Fish can “look like” a Fish, an Animal, and even a Swimmer. You can use this when ever you need to be passed to a method.
A Fish IS-A Fish
A Fish IS-A Animal
A Fish IS-A Swimmer
Fish f = new Fish();
Animal a = f;
Swimmer s = f;
Object o = f;
Type Casting
Assume that you have a method for a class definition, like Shape2D, then a child class Shape3D. If Shape2D has a method to find the distance, you can call it by the Shape3D object if you want to, you just need to cast the Shape3D object as a Shape2D object, which you can because it is derived from it. We’ll look at that in a second.
For a simpler example let’s look at the Object class. Every class is a extends the Object class as some point in its hierarchy, either directly or indirectly. This means we can write a method which accepts a parameter of type Object, and we can pass any object into that class.
This is essentially what the print()
and println()
methods do. They are overloaded to take in all types of primitive datatypes. however, Java cannot know about every possible Class that could ever conceived. So instead, it accepts a parameter of type Object, which allows it to take all Class types.
string println(Object o) {
return o.toString();
}
As you can see, it takes the parameter o, of type Object, and then returns the string from it. It does so, by calling the toString()
method which is part of every class, due to the Object class.
Let’s look at our previous example of the Shape2D and Shape3D classes. While not common, there may be times I want to calculate the 2D distance of a 3D object, so I can have both class definitions like below.
public class Shape2D {
private double xCoord;
private double yCoord;
double distance(Shape2D s2) {
}
}
public class Shape3D extends Shape2D {
private double zCoord;
double distance(Shape3D s2) {
}
}
Then for a Shape3D object, I can pass it as a Shape2D object, like you see below.
Shape2D square = new Shape2D();
Shape3D cube = new Shape3D();
Shape3D box = new Shape3D();
// square only can take a Shape2D, so it is OK with
// taking a Shape3D and using it as a Shape2D which
// it was derived from
double distance1 = square.distance(cube);
// box and cube are both Shape3D objects, but we're
// forcing them to use the Shape2D method, by using
// type casting
double distance2 = box.distance((Shape2D)cube);
Understanding Polymorphism in Java was originally found on Access 2 Learn