Middle
What is the difference between an abstract class and an interface?
sobes.tech AI
Answer from AI
Abstract class — is a class that can contain both implemented methods and abstract methods (without implementation). It serves as a base for inheritance and can contain state (fields).
Interface — is a contract that defines a set of methods without implementation (in the traditional sense). A class implementing an interface must implement all its methods.
Main differences:
- An abstract class can contain implementation and state, an interface — only method signatures (in some languages, interfaces can contain default methods).
- A class can inherit from only one abstract class but can implement multiple interfaces.
- An abstract class provides partial implementation, an interface — only the contract.
Example in Java:
abstract class Animal {
void eat() { System.out.println("Eating"); }
abstract void sound();
}
interface Flyable {
void fly();
}
class Bird extends Animal implements Flyable {
void sound() { System.out.println("Chirp"); }
public void fly() { System.out.println("Flying"); }
}