Inheritance
1. What Is Inheritance? (beginner)
Inheritance = child gets parent's stuff free (extends). Like son inherits father's house + adds floor! Reuse without copy-paste. Java: ONE parent per class (single!) + many via interfaces!
2. Code — Reuse Proof!
class Animal { // parent (superclass!)
String name;
void eat() { System.out.println(name + " eats"); }
}
class Dog extends Animal { // child (subclass!) — inherits name + eat()!
void bark() { System.out.println(name + " barks"); }
}
Dog d = new Dog();
d.name = "Tommy"; // from Animal!
d.eat(); // from Animal! (reused!)
d.bark(); // own!
IS-A: Dog IS-A Animal (upcast ok: Animal a = new Dog();).
3. Rules (exam traps!)
extendsONE class only (noextends A, B— use interfaces!).- Child gets public/protected (NOT private!).
- Constructor NOT inherited (but parent ctor runs first via
super()!). finalclass = no children (Stringis final!).
4. Benefits
Reuse + override (customize!) + polymorphism (parent ref, child behaviour — next topics!).
5. Exam Points
- Program + IS-A + diagram — 7 marks, very frequent.
- Single-inheritance + private-not-inherited — 3-5 marks, favourite traps.