Junior — Middle
How does the implementation of methods in an abstract class differ from defining methods in an interface?
sobes.tech AI
Answer from AI
Main differences between implementing methods in an abstract class and defining methods in an interface in Java:
- An abstract class can contain both abstract methods (without implementation) and methods with implementation. It can have state (fields).
- An interface before Java 8 could only contain method declarations without implementation. Starting from Java 8, interfaces can contain default methods (with implementation) and static methods.
Example of an abstract class:
public abstract class Animal {
public abstract void makeSound();
public void breathe() {
System.out.println("Breathing");
}
}
Example of an interface with a default method:
public interface Animal {
void makeSound();
default void breathe() {
System.out.println("Breathing");
}
}
Key differences:
- A class can inherit only one abstract class but can implement multiple interfaces.
- An abstract class can contain state, an interface — no (only constants).
- Interfaces are more oriented towards contracts, abstract classes — towards partial implementation.