Interfaces and Abstract Classes
Interfaces and Abstract Classes in Java
Interfaces An interface defines a contract — a set of method signatures that implementing classes must provide. Since Java 8, interfaces may also have default and static methods.
interface Drawable { void draw(); }
class Circle implements Drawable { … }A class can implement multiple interfaces.
Abstract classes An abstract class cannot be instantiated and may contain abstract methods (no body) that subclasses must implement. It can also contain concrete methods and fields.
abstract class Vehicle {
abstract int maxSpeed();
void describe() { System.out.println("Speed: " + maxSpeed()); }
}Polymorphism Both mechanisms support polymorphism — treating objects of different types uniformly through a common supertype:
List<Drawable> shapes = List.of(new Circle(), new Square());
shapes.forEach(Drawable::draw);Key points:
- Use an interface when unrelated classes should share behaviour.
- Use an abstract class when related classes share state and some implementation.
- Interfaces cannot have instance fields (only constants).
Code Examples
interface Shape {
double area();
default String describe() {
return getClass().getSimpleName() + " with area " + String.format("%.2f", area());
}
}
class Circle implements Shape {
private double radius;
Circle(double radius) { this.radius = radius; }
public double area() { return Math.PI * radius * radius; }
}
class Square implements Shape {
private double side;
Square(double side) { this.side = side; }
public double area() { return side * side; }
}
public class ShapeDemo {
public static void main(String[] args) {
Shape[] shapes = { new Circle(5), new Square(4) };
for (Shape s : shapes) {
System.out.println(s.describe());
}
}
}Both classes implement the Shape interface. The default method is inherited and calls the overridden area() polymorphically.
abstract class Employee {
protected String name;
protected double baseSalary;
Employee(String name, double baseSalary) {
this.name = name;
this.baseSalary = baseSalary;
}
abstract double calculateBonus();
double totalCompensation() {
return baseSalary + calculateBonus();
}
}
class Manager extends Employee {
Manager(String name, double base) { super(name, base); }
double calculateBonus() { return baseSalary * 0.20; }
}
class Engineer extends Employee {
Engineer(String name, double base) { super(name, base); }
double calculateBonus() { return baseSalary * 0.10; }
}
public class PayrollDemo {
public static void main(String[] args) {
Employee[] staff = { new Manager("Alice", 80000), new Engineer("Bob", 70000) };
for (Employee e : staff) {
System.out.printf("%s: $%.0f%n", e.name, e.totalCompensation());
}
}
}The abstract class provides shared fields and a concrete totalCompensation() method. Subclasses supply calculateBonus() implementations.
Quick Quiz
1. How many interfaces can a Java class implement?
2. Can an abstract class have concrete (implemented) methods?
Was this lesson helpful?