Lesson 14: Polymorphism, Interfaces and Abstract Classes
Polymorphism means that one piece of code can work with objects of many classes, and it is the payoff for inheritance. A variable declared as a superclass type, such as Animal a = new Dog("Rex");, can hold any subclass object, and a method that takes an Animal parameter can be called with a Dog, a Cat, or any other Animal. When a method is called on such a variable, Java uses the object's actual class to decide which version runs — this is called dynamic binding — so the same call, a.speak(), can produce 'Woof' for a Dog and 'Meow' for a Cat. The reference type decides what you are allowed to call; the object type decides what actually happens.
That distinction is the key to tracing polymorphic code. The compiler checks every method call against the declared type of the variable: if the variable is declared as Animal, you can only call methods that Animal has, even if the object is a Dog with extra methods of its own. Trying to call a Dog-only method through an Animal variable is a compile-time error, and the fix is a cast, as in ((Dog) a).bark(), which tells the compiler to trust that the object really is a Dog. A cast to the wrong type compiles but fails at run time with a ClassCastException, so it should only be used when you are sure of the object's class.
An abstract class is a class that cannot be instantiated, declared with the abstract keyword, and used as a base for subclasses that fill in the missing pieces. It can contain abstract methods, methods declared without a body, which every concrete subclass must implement. An interface goes further: it declares a set of methods that a class promises to implement, and a class implements it with the implements keyword. A class can extend only one superclass but can implement many interfaces, which is how Java gets the benefits of multiple inheritance without its complications.
Interfaces are used for abilities that cut across class hierarchies: Comparable for objects that can be ordered, or a custom Drawable interface for anything that can be drawn. Code that works with an interface type can accept any object whose class implements it, whatever its superclass. When you design with interfaces, think about the contract: the interface names the methods and their signatures, and every implementing class must honour them. In free-response answers, the important checks are the keywords — abstract, implements, extends — and the rule that an abstract class cannot be created with new.
The Comparable interface is the standard way to make objects orderable, and it is worth studying as an example of how interfaces are used in practice. A class that implements Comparable must provide compareTo, which returns a negative number when the object is smaller than the argument, zero when they are equal, and a positive number when it is larger. Sorting methods in the standard library rely on this contract, so a compareTo that is inconsistent — for example, one that says A is less than B and also that B is less than A — will produce wrong results. An abstract class can also declare abstract methods that its subclasses must implement, and the difference from an interface is that the abstract class can also provide fields and concrete methods that all its subclasses share.
A worked example
Worked example: the interface below promises a single method, area, and two unrelated classes implement it. A method that takes a Shape can then work with either, and dynamic binding picks the right area method for each object.
public interface Shape
{
double area();
}
public class Circle implements Shape
{
private double radius;
public Circle(double radius)
{
this.radius = radius;
}
public double area()
{
return Math.PI * radius * radius;
}
}
public class Rectangle implements Shape
{
private double width;
private double height;
public Rectangle(double width, double height)
{
this.width = width;
this.height = height;
}
public double area()
{
return width * height;
}
}
// Shape s = new Circle(2.0); s.area() returns about 12.57
The variable s is declared as Shape, so only Shape methods can be called on it, but the object is a Circle, so the Circle version of area runs and returns π × 4, about 12.57. Storing a Rectangle in the same variable would run the Rectangle version instead, with no change to the calling code — that is polymorphism. A class that implements Shape must provide area with exactly the signature in the interface, or it will not compile.
Key Terms
- Polymorphism
- One reference type working with objects of many classes, with the object's class deciding behaviour.
- Dynamic binding
- Choosing which method version runs at run time, based on the object's actual class.
- Abstract class
- A class that cannot be instantiated and may contain abstract methods for subclasses to implement.
- Interface
- A set of method signatures a class promises to implement, declared with interface and used with implements.
- Cast
- An explicit conversion of a reference to a subclass type, such as (Dog) a.
Discussion Questions
- What does the declared type of a variable control, and what does the object's class control?
- Why can a class implement many interfaces but extend only one superclass?
- When would you use an interface instead of an abstract class?
Practice Questions
- Animal a = new Dog("Rex"); Which methods can be called on a?
- What happens if you cast an Animal variable holding a Cat to Dog?
- Can you write new Shape() if Shape is an interface?
- A class implements Comparable. What must it provide?
- Two objects are stored in Animal variables, one a Dog and one a Cat. What does a.speak() do for each?
Show answers
- Only the methods declared in Animal, or inherited by it, as checked at compile time.
- It compiles but throws a ClassCastException at run time.
- No; interfaces cannot be instantiated, only implemented.
- A compareTo method with the signature declared in the interface.
- It runs the Dog version for the Dog object and the Cat version for the Cat object, by dynamic binding.