Junior — Middle
How does using abstract classes differ from interfaces in object-oriented programming?
sobes.tech AI
Answer from AI
Abstract classes and interfaces are two ways to describe contracts and behaviors in object-oriented programming, but they have key differences:
-
Abstract class can contain both implemented methods and abstract methods (without implementation). It serves as a base class that can be inherited. An abstract class can have state (fields).
-
Interface only describes a set of methods (in modern languages, interfaces can contain default implementations, but essentially it is a contract). An interface does not contain state.
Main differences:
- Inheritance: A class can inherit from only one abstract class but can implement multiple interfaces.
- State: An abstract class can hold state, an interface cannot.
- Purpose: An abstract class is used when there is a common implementation and state, while an interface is for defining a contract without implementation.
Example in Java:
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");
}
}
Here, Animal is an abstract class with partial implementation, and Flyable is an interface defining the ability to fly.