Abstraction
Abstraction means showing what an object does and hiding how it does it. You press a car's brake pedal without knowing how the hydraulics work. In Java, abstraction is built with abstract classes and interfaces.
Abstract classes
An abstract class is an incomplete class: you cannot create objects of it, but subclasses can extend it.
abstract class Shape {
String name;
Shape(String name) {
this.name = name;
}
abstract double area(); // no body: each shape must provide one
void describe() { // a normal, shared method
System.out.printf("%s has area %.2f%n", name, area());
}
}
class Circle extends Shape {
double r;
Circle(double r) { super("Circle"); this.r = r; }
@Override
double area() { return Math.PI * r * r; }
}
class Rectangle extends Shape {
double l, w;
Rectangle(double l, double w) { super("Rectangle"); this.l = l; this.w = w; }
@Override
double area() { return l * w; }
}
Shape[] shapes = { new Circle(7), new Rectangle(4, 5) };
for (Shape s : shapes) s.describe();
// new Shape("x"); // error: Shape is abstract; cannot be instantiated
Circle has area 153.94
Rectangle has area 20.00
Rules
- An abstract method has no body and ends with
;. - A class with any abstract method must be declared
abstract. - A concrete subclass must override every abstract method, or be abstract itself.
- An abstract class can have fields, constructors and normal methods.
Interfaces
An interface is a contract: a list of methods a class promises to provide. It describes a capability ("can be paid", "can be printed", "can be compared").
interface Payable {
double amountDue(); // public and abstract automatically
}
interface Printable {
void print();
}
class Invoice implements Payable, Printable {
private final double amount;
Invoice(double amount) { this.amount = amount; }
@Override
public double amountDue() { return amount * 1.18; }
@Override
public void print() { System.out.println("Invoice due: " + amountDue()); }
}
- A class
implementsan interface and must provide all its abstract methods, aspublic. - A class can implement many interfaces: this is how Java gets the benefit of multiple inheritance without its problems.
- An interface can
extendother interfaces. - Interface fields are automatically
public static final(constants).
Programming to an interface
Payable[] bills = { new Invoice(1000), new Invoice(250) };
double total = 0;
for (Payable p : bills) total += p.amountDue();
The loop works with any class that implements Payable, including ones written later.
default and static methods (Java 8+)
interface Greeter {
String name();
default String greet() { // has a body; implementers may override
return "Hello, " + name();
}
static Greeter of(String n) { // called as Greeter.of("Asha")
return () -> n;
}
}
A default method lets an interface gain a new method without breaking every class that already implements it. Interfaces can also have private helper methods (Java 9+).
Functional interfaces
An interface with exactly one abstract method is a functional interface. It can be implemented with a lambda (see the Lambdas topic). Greeter.of above returns one. Runnable, Comparator and Comparable are well-known examples.
Abstract class or interface?
| Abstract class | Interface | |
|---|---|---|
| Keyword to use it | extends | implements |
| How many per class | one | many |
| Fields | any kind | constants only |
| Constructors | yes | no |
| Methods | abstract and normal | abstract, default, static, private |
| Relationship | "is-a" with shared code | "can-do" capability |
Rule of thumb: use an interface to describe a capability many unrelated classes can have; use an abstract class when closely related classes share fields and code.
Example: the Comparable interface
class Student implements Comparable<Student> {
String name;
int marks;
Student(String name, int marks) { this.name = name; this.marks = marks; }
@Override
public int compareTo(Student other) {
return Integer.compare(other.marks, this.marks); // higher marks first
}
}
Arrays.sort(students) now sorts by marks, highest first.
Common mistakes
- Trying
new Shape(...)on an abstract class. - Implementing an interface method without
public: "attempting to assign weaker access privileges". - Forgetting one abstract method, so the compiler says the class "is not abstract and does not override abstract method".
- Writing
class A implements BwhenBis a class (useextends), orextendswith an interface. - Putting changeable state in an interface: its fields are constants.
Key points
- An abstract class cannot be instantiated; its abstract methods must be overridden by concrete subclasses.
- An interface is a contract; a class can implement many interfaces.
- Interface methods are public; fields are
public static final. defaultmethods give interfaces bodies;staticmethods are called on the interface.- A functional interface has one abstract method and works with lambdas.
Practice questions
1. Can an abstract class have a constructor? Why would it?
Yes. It runs when a subclass object is created (through super(...)) and sets up the shared fields.
2. Write an interface Discountable with double discount() and a class Book that gives 10% off its price.
interface Discountable {
double discount();
}
class Book implements Discountable {
double price;
Book(double price) { this.price = price; }
@Override
public double discount() { return price * 0.10; }
}3. Why can a class implement two interfaces but not extend two classes?
Two superclasses could both supply fields and method bodies with the same names, which would be ambiguous. Interfaces mostly declare methods; if two default methods clash, Java forces the class to override and choose.
4. What is a functional interface? Give one example from Java.
An interface with exactly one abstract method, such as Runnable (run()) or Comparator<T> (compare).
5. A class has one abstract method and is not declared abstract. What happens?
It does not compile: a class with an abstract method must itself be declared abstract.