Middle
In which cases should an abstract class be used, and in which cases — an interface?
sobes.tech AI
Answer from AI
An abstract class should be used when:
- You need to define common base functionality with the ability to implement some methods.
- You need to share state (fields) among subclasses.
- It is assumed that subclasses will have a close "is-a" relationship with the base class.
- You want the ability to add new methods to the abstract class in the future without breaking existing implementations.
An interface should be used when:
- You need to define a behavior contract without any implementation.
- Classes can implement multiple different contracts (interfaces), as Java does not support multiple inheritance of classes.
- You want to separate the definition of functionality from its implementation.
- Flexibility and cohesion between system components are required.
Example of an abstract class:
// Abstract class with common fields and a partially implemented method
abstract class Animal {
protected String name;
public Animal(String name) {
this.name = name;
}
public abstract void makeSound(); // Method without implementation
public void eat() { // Implemented method
System.out.println(name + " is eating.");
}
}
Example of an interface:
// Interface defining a behavior contract
interface Flyable {
void fly(); // Method without implementation
}
Summary table:
| Attribute | Abstract Class | Interface |
|---|---|---|
| Method Implementation | Can contain both implemented and abstract methods | Only method declarations (before Java 8), can have default and static methods (since Java 8) |
| State | Can have fields (state) | Cannot have instance fields (only public static final) |
| Multiple inheritance | No | Yes |
| Relationship | "is-a" | "has-a" / contract |
| Adding new methods | Possible without breaking existing subclasses | May require changes to implementing classes (before Java 8), easier with default methods (since Java 8) |