Sub topic 1
Why Abstraction? Describing What Without How
Abstraction means describing what something does without saying how it does it. A driver knows that a car has a brake pedal. The driver does not need to know how the brakes work inside. Code works the same way. You can write code that says "every shape has an area" before you know which shapes will exist.
Java gives you two tools for this: abstract classes and interfaces. This chapter covers abstract classes.
Declaring an Abstract Class
An abstract class is a class marked with the abstract keyword. It describes a general idea, such as "a shape." You cannot create an object directly from an abstract class. It exists so that other classes can extend it.
Abstract Methods: Promises Without Bodies
An abstract method is a method with no body. It ends with a semicolon instead of curly braces. It is a promise: "every subclass will supply this method." Only an abstract class can hold abstract methods.
Writing a Concrete Subclass
A concrete subclass is a normal class that extends the abstract class and gives a body to every abstract method. If it skips one, the code will not compile.
Constructors, Fields, and Shared Code
An abstract class can still have fields (stored data), a constructor, and regular methods with bodies. Subclasses reuse that shared code. A subclass calls the parent constructor with super(...).
abstract class Shape {
private final String name;
protected Shape(String name) {
this.name = name;
}
public abstract double area();
public String describe() {
return name + " with area " + area();
}
}
class Circle extends Shape {
private final double radius;
Circle(double radius) {
super("Circle");
this.radius = radius;
}
@Override
public double area() {
return Math.PI * radius * radius;
}
}
public class Main {
public static void main(String[] args) {
Shape s = new Circle(2.0);
System.out.println(s.describe());
// Shape bad = new Shape("x"); // compile error: Shape is abstract
}
}The program prints Circle with area 12.566370614359172. The describe method lives in Shape, but it calls the area method that Circle supplies.
Exercise
You add a class Square extends Shape but do not write an area method. What happens, and why?
Show answer
The code does not compile. area is abstract in Shape, so every concrete subclass must supply a body for it. To fix it, add an area method to Square, or declare Square abstract.