Hiprup

What is the difference between abstract class and interface in Java?

Both define a contract but differ in capability and intent.

Abstract class — can have abstract and concrete methods, instance state, constructors, and any access modifier. A class can extend only one. Best for "is-a" with shared base behavior.

Interface — defines a contract; methods are public abstract by default. Java 8+ allows default and static methods; Java 9+ allows private methods. A class can implement many. Best for capability/"can-do" types.

Rule of thumb — pick interfaces by default; reach for abstract classes when you need shared state or partial implementation.

// Interface - defines capability
public interface Flyable {
    void fly();  // abstract by default
    default String getType() { return "Flying object"; } // Java 8 default method
}

public interface Swimmable {
    void swim();
}

// Abstract class - shared implementation for related classes
public abstract class Animal {
    protected String name;
    public Animal(String name) { this.name = name; } // Constructor!
    public String getName() { return name; }
    public abstract void makeSound(); // Subclasses must implement
}

// Multiple interface implementation, single class inheritance
public class Duck extends Animal implements Flyable, Swimmable {
    public Duck(String name) { super(name); }
    @Override public void makeSound() { System.out.println("Quack"); }
    @Override public void fly() { System.out.println(name + " flies"); }
    @Override public void swim() { System.out.println(name + " swims"); }
}

Flyable and Swimmable are interfaces defining capabilities. Animal is an abstract class with state (name), a constructor, a concrete method (getName), and an abstract method (makeSound).

Duck extends Animal (single inheritance) and implements both interfaces (multiple inheritance). Duck must implement all abstract methods from both the class and interfaces.

Since Java 8, know the new capabilities of interfaces (default methods, static methods, private methods in Java 9). The key remaining difference: interfaces cannot have state or constructors.

Use the capability (interface) vs shared implementation (abstract class) design guideline.