What is the difference between an abstract class and an interface in Java, and how do you use each one?
An abstract class is a class that cannot be instantiated and exists to be extended. It can hold instance state, it can have a constructor, and it can carry concrete helper methods that subclasses inherit. An interface is a contract: it describes what a type can do, and it can also supply default and static method bodies, but it cannot hold instance state.
That single difference — state — is what everything else follows from. An abstract class can promise that every subclass has a particular field and that it is initialised in the superclass constructor. An interface cannot, because there is nowhere to put an instance field and no constructor to run.
public class Main {
public static void main(String[] args) {
// An interface type can hold any implementation.
Vehicle car = new Car("red");
Vehicle bike = new Bike("blue");
System.out.println("car : " + car.describe() + ", doors=" + car.doors());
System.out.println("bike : " + bike.describe() + ", doors=" + bike.doors());
}
}
// An interface defines a contract and may provide default behaviour.
interface Vehicle {
String describe();
default int doors() {
return 4;
}
}
// An abstract class can hold state and constructor logic.
abstract class BaseVehicle implements Vehicle {
protected final String colour;
BaseVehicle(String colour) {
this.colour = colour;
}
@Override
public String describe() {
return getClass().getSimpleName() + " in " + colour;
}
}
class Car extends BaseVehicle {
Car(String colour) {
super(colour);
}
}
class Bike extends BaseVehicle {
Bike(String colour) {
super(colour);
}
@Override
public int doors() {
return 0;
}
}The output shows both mechanisms at work. The describe implementation lives in the abstract class and uses the colour field, which only an abstract class could hold. The doors behaviour comes from the interface's default method, and Bike overrides it without the abstract class having to know anything about it.
The other differences to name: an abstract class has one superclass, an interface has many. A class can extend one abstract class and implement several interfaces at the same time. And access modifiers on interface members are implicitly public, whereas an abstract class may use any modifier.