Senior
What is the difference between an abstract class and an interface?
sobes.tech AI
Answer from AI
An abstract class and an interface are two ways to describe contracts and behavior in Java, but they have key differences:
-
Abstract class can contain both abstract methods (without implementation) and methods with implementation, as well as fields with state. It is used when you need to define a base implementation and common state for subclasses.
-
Interface originally contained only method declarations without implementation (before Java 8), but starting with Java 8, interfaces can contain methods with default implementations (default methods) and static methods. An interface cannot contain state (data fields), except for constants (static final).
Other differences:
- A class can inherit from only one abstract class but can implement multiple interfaces.
- An abstract class can have constructors, whereas an interface cannot.
Example:
abstract class Animal {
abstract void makeSound();
void breathe() {
System.out.println("Breathing...");
}
}
interface Flyable {
void fly();
}
class Bird extends Animal implements Flyable {
void makeSound() {
System.out.println("Chirp");
}
public void fly() {
System.out.println("Flying");
}
}