Sobes.tech
Middle+

What is the difference between interfaces and abstract classes in Java (starting from Java 8)?

sobes.tech AI

Answer from AI

Starting from Java 8, interfaces and abstract classes have the following key differences:

  • Inheritance:

    • An abstract class can inherit from only one class (single inheritance).
    • An interface can inherit from multiple interfaces (multiple inheritance).
  • Method implementation:

    • An abstract class can contain both abstract and concrete methods with implementations.
    • An interface with Java 8 can contain default methods (methods with default implementation) and static methods.
  • Fields:

    • An abstract class can have fields of any type and modifiers.
    • An interface can only contain constants (public static final).
  • Constructors:

    • An abstract class can have constructors.
    • An interface cannot have constructors.
  • Usage:

    • Abstract classes are used when creating a base class with common implementation and state.
    • Interfaces are used to define a contract that different classes can implement, often to ensure multiple inheritance of behavior.

Example of an interface with a default method:

public interface MyInterface {
    void abstractMethod();

    default void defaultMethod() {
        System.out.println("Default implementation");
    }
}

Example of an abstract class:

public abstract class MyAbstractClass {
    protected int value;

    public MyAbstractClass(int value) {
        this.value = value;
    }

    public abstract void abstractMethod();

    public void concreteMethod() {
        System.out.println("Value: " + value);
    }
}