Methods of Java · Introduction to Java Programming

Inheritance

Watch lectures

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!)

  • extends ONE class only (no extends A, B — use interfaces!).
  • Child gets public/protected (NOT private!).
  • Constructor NOT inherited (but parent ctor runs first via super()!).
  • final class = no children (String is 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.
Free AppAndroid App

Coursify Android App

Generate AI courses, take quick quizzes between classes, and master complex engineering concepts on the go.

← All Introduction to Java Programming modules