Junior — Middle
Can an abstract class where all methods are abstract be replaced by an interface?
sobes.tech AI
Answer from AI
Yes, an abstract class in which all methods are abstract can essentially be replaced by an interface.
Reasons:
- An interface is intended to declare only abstract methods (before Java 8), which matches the description of a class where all methods are abstract.
- Interfaces allow for multiple inheritance, unlike classes.
However:
- If an abstract class contains fields or methods with implementations, it cannot be replaced by an interface without losing functionality.
- Starting from Java 8, interfaces can contain methods with implementations (default methods), which further blurs the lines between interfaces and abstract classes.
Example of replacement:
// Abstract class
abstract class Shape {
abstract void draw();
}
// Interface
interface Shape {
void draw();
}