# Composition vs Inheritance
## Inheritance ("is-a")
```java
class Animal {
void eat() { System.out.println("This animal eats food"); }
}
class Dog extends Animal {
void bark() { System.out.println("Woof!"); }
}
Dog myDog = new Dog();
myDog.eat(); // Inherited
myDog.bark(); // Own method
```
## Composition ("has-a")
```java
class Engine {
void start() { System.out.println("Engine started"); }
}
class Car {
private Engine engine = new Engine();
void startCar() {
engine.start();
System.out.println("Car is running");
}
}
```
## Key Differences
| | Inheritance | Composition |
|---|---|---|
| Relationship | "is-a" (Dog is an Animal) | "has-a" (Car has an Engine) |
| Coupling | Tight (parent-child) | Loose (delegates) |
| Flexibility | Vertical extension | Horizontal delegation |
## When to Use Each
**Inheritance** — clear "is-a" relationship, sharing code across related classes, subclasses are truly specialized versions.
**Composition** — need flexibility, "has-a" relationship, want to avoid the "fragile base class" problem.
**Rule of thumb:** "Favor composition over inheritance" — composition leads to more flexible and maintainable code.