Abstract class vs Interface

Heeah
2 min readDec 30, 2023

--

Abstraction is one of the Object-Oriented programming key features. It allows us to hide the implementation complexities just by providing functionalities via simpler interfaces. In Java, we achieve abstraction by using either an interface or an abstract class.

Key Points

1. abstract classes can have both abstract methods (without a body) and methods with implementation.
2. interfaces can only have abstract methods, with the exception of default methods and static methods in Java 8 and beyond.
3. A class can implement multiple interfaces but can only extend one abstract class.
4. abstract classes can maintain state through member variables, but interfaces cannot, although they can have static final variables.

// Define an abstract class
abstract class Vehicle {
protected String brand; // Abstract class can have member variables

// Abstract class can have a constructor
public Vehicle(String brand) {
this.brand = brand;
}

// Abstract class can have concrete methods
public void start() {
System.out.println("This " + brand + " is starting.");
}

// Abstract class can have abstract methods
public abstract void honk();
}

// Define an interface
interface Flyable {
// Interfaces can have abstract methods
void fly();

// Interfaces can have default methods (Java 8+)
default void land() {
System.out.println("I am landing.");
}
}

// A class that extends the abstract class and implements the interface
class FlyingCar extends Vehicle implements Flyable {

public FlyingCar(String brand) {
super(brand);
}

// Implement the abstract method from Vehicle
public void honk() {
System.out.println("This " + brand + " is honking.");
}

// Implement all abstract methods from Flyable
public void fly() {
System.out.println("This " + brand + " is flying.");
}
}

public class Main {
public static void main(String[] args) {
FlyingCar car = new FlyingCar("Terrafugia");

// Using the method from abstract class
car.start();

// Using the method from interface
car.fly();

// Using the default method from interface
car.land();

// Using the method implemented in the subclass
car. Honk();
}
}

https://www.javaguides.net/2023/11/abstract-class-vs-interface-in-java.html

--

--