What is the difference between an abstract class and an interface in Java, and how do you use each one?
They are both ways of saying "here is the shape of this thing", and they differ in what they are allowed to hold.
An abstract class is a class that cannot be made into an object, because it is incomplete in some way. It can hold state, it can have a constructor, it can have ordinary concrete methods as well as abstract ones, and it can extend another class. A class can extend only one abstract class.
An interface is a pure contract. Since Java 8 it can have default methods and static methods, and it can have constants, but it cannot have an ordinary instance field with state that each object holds. A class can implement any number of interfaces.
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("black");
System.out.println("car : " + car.describe());
System.out.println("bike : " + bike.describe());
// The type decides which methods you may call.
System.out.println("wheels : " + car.getWheels());
}
}
interface Vehicle {
String getName();
// A default method is shared by every implementation.
default String describe() {
return "a " + getName() + " with " + getWheels() + " wheels";
}
int getWheels();
}
class Car implements Vehicle {
private final String colour;
Car(String colour) {
this.colour = colour;
}
public String getName() {
return "car";
}
public int getWheels() {
return 4;
}
public String getColour() {
return this.colour;
}
}
class Bike implements Vehicle {
private final String colour;
Bike(String colour) {
this.colour = colour;
}
public String getName() {
return "bike";
}
public int getWheels() {
return 2;
}
}
The next question in this topic looks at how to choose between them.