Sub topic 8
Programming to an Abstract Type
You have already written abstract classes and interfaces. This chapter shows the main reason to use them: you can write code that works with any class that fits the type, without knowing in advance which class it will get.
What "Programming to an Abstract Type" Means
A reference is a variable that points to an object. Every reference has a declared type, which is the type written in the variable's declaration. The object it points to has an actual type, which is the class used after new.
Shape s = new Circle(2.0);Here the declared type is Shape and the actual type is Circle.
Programming to an abstract type means you give your variables, parameters, and lists an abstract class or interface as their declared type. You don't use a specific concrete class. Your code then depends only on what the type promises, so it keeps working when someone adds a new class later.
Polymorphism means one reference can point to objects of many different classes, and each object answers a method call in its own way. The word means "many forms."
A Worked Example: Many Shapes, One Loop
This program uses one abstract class and two concrete subclasses. The totalArea method never mentions Circle or Rectangle.
import java.util.List;
abstract class Shape {
public abstract double area();
}
class Circle extends Shape {
private final double radius;
Circle(double radius) {
this.radius = radius;
}
@Override
public double area() {
return Math.PI * radius * radius;
}
}
class Rectangle extends Shape {
private final double width;
private final double height;
Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
public double area() {
return width * height;
}
}
public class Main {
static double totalArea(List<Shape> shapes) {
double total = 0;
for (Shape shape : shapes) {
total += shape.area();
}
return total;
}
public static void main(String[] args) {
List<Shape> shapes = List.of(
new Circle(1.0),
new Rectangle(2.0, 3.0),
new Circle(0.5)
);
System.out.printf("Total area: %.2f%n", totalArea(shapes));
// prints: Total area: 10.71
}
}Look at the line total += shape.area();. The variable shape has the declared type Shape. On the first loop pass it points to a Circle, and on the second it points to a Rectangle. Java runs the right area() each time.
How Java Picks the Method
Java decides which method body to run while the program runs, based on the object's actual type. This is called dynamic dispatch. The compiler only checks that Shape has an area() method. The choice of which version to call waits until the call happens.
Adding a New Class Without Changing Old Code
Say you need triangles. You write one new class:
class Triangle extends Shape {
private final double base;
private final double height;
Triangle(double base, double height) {
this.base = base;
this.height = height;
}
@Override
public double area() {
return 0.5 * base * height;
}
}Add new Triangle(4.0, 2.0) to the list and totalArea handles it. You did not edit totalArea at all. This is the main payoff. Code written against the abstract type stays the same while new classes appear.
The Same Idea With Interfaces
Interfaces work the same way. A parameter whose type is an interface accepts any object of a class that implements it.
interface Greeter {
String greet(String name);
}
class EnglishGreeter implements Greeter {
@Override
public String greet(String name) {
return "Hello, " + name;
}
}
class SpanishGreeter implements Greeter {
@Override
public String greet(String name) {
return "Hola, " + name;
}
}
public class Main {
static void welcome(Greeter greeter, String name) {
System.out.println(greeter.greet(name));
}
public static void main(String[] args) {
welcome(new EnglishGreeter(), "Ana"); // prints: Hello, Ana
welcome(new SpanishGreeter(), "Ana"); // prints: Hola, Ana
}
}The welcome method can switch languages without being changed. The caller picks which object to pass in.
What You Can and Cannot Call
The declared type decides which methods the compiler lets you call. The actual type decides which body runs. Beginners often mix these two up.
| Question | Decided by | When |
|---|---|---|
| Is this method call allowed? | Declared type | At compile time |
| Which method body runs? | Actual type | At run time |
Suppose Circle had an extra method getRadius() that Shape does not have:
Shape s = new Circle(2.0);
s.area(); // OK: Shape declares area()
// s.getRadius(); // compile error: Shape has no getRadius()The object really is a Circle, but the compiler only knows it as a Shape. It does not let you call methods that Shape doesn't promise.
Getting Back to the Concrete Type
If you truly need the subclass method, check the type first with instanceof. Java 16 and later let you name the result in the same step. This is called pattern matching:
if (s instanceof Circle c) {
System.out.println(c.getRadius());
}Common Mistakes
- Declaring the concrete type everywhere. If you write
Circle c = new Circle(1.0);in a method that only needsarea(), that method can no longer accept other shapes. - Expecting fields to act like methods. Dynamic dispatch applies to instance methods. Fields and
staticmethods are chosen by the declared type, not by the actual object. - Trying to create the abstract type.
new Shape()will not compile. Abstract types work as declared types for references. The objects themselves must come from concrete classes. - Casting without checking. Writing
(Circle) swhenspoints to aRectanglethrows aClassCastExceptionwhile the program runs. Check withinstanceoffirst.
Exercise
Given Shape s = new Rectangle(2.0, 5.0);, what does s.area() return, and which class's area() method runs? Would Rectangle r = s; compile?
Show answer
It returns 10.0, and Rectangle.area() runs because the actual object is a Rectangle (dynamic dispatch). Rectangle r = s; does not compile, because the declared type of s is Shape and the compiler cannot be sure it is a Rectangle. You would need a cast such as Rectangle r = (Rectangle) s;, ideally after an instanceof check.
Exercise
Write a method printAll(List<Greeter> greeters, String name) that prints each greeter's greeting for the given name. Why can you add a new FrenchGreeter class later without changing this method?
Show answer
static void printAll(List<Greeter> greeters, String name) { for (Greeter g : greeters) { System.out.println(g.greet(name)); } } — The method depends only on the Greeter interface. Any new class that implements Greeter can go in the list, and dynamic dispatch runs that class's own greet() method.