Inheritance — extends, super & Hierarchies

Inheritance — extends, super ও class-এর বংশধারা

Read: ~32 min Advanced 5 practice problems Live code runner

1. The Is-A Relationship

Inheritance expresses an "is-a" relationship. A Rickshaw is a Vehicle. A SavingsAccount is a BankAccount. When one class is naturally a specialisation of another, Java lets the specialised class inherit fields and methods from the general one, then add or override what is different. The keyword is extends.

Inheritance মানে "is-a" সম্পর্ক। Rickshaw একটি Vehicle; SavingsAccount একটি BankAccount। এক class যখন অন্যটির বিশেষায়িত রূপ, তখন Java-তে সাধারণ class থেকে field ও method উত্তরাধিকার সূত্রে পাওয়া যায় — keyword extends। যা আলাদা তা subclass-এ override বা নতুন করে যোগ করা যায়।

Java supports single class inheritance — one class can extend exactly one direct parent — but arbitrarily deep hierarchies are allowed, and every class (directly or indirectly) extends java.lang.Object, the root of all Java types.

2. A First Hierarchy

Consider transport in Dhaka. Every vehicle has a type and can move. A rickshaw is a kind of vehicle; so is a CNG auto-rickshaw; so is a Toyota Corolla. In code:

Main.java
class Vehicle {
    String type;
    Vehicle(String type) { this.type = type; }
    void move() { System.out.println(type + " is moving."); }
}

class Rickshaw extends Vehicle {
    String driver;
    Rickshaw(String driver) {
        super("Rickshaw");       // must be first statement
        this.driver = driver;
    }
    void ringBell() { System.out.println(driver + " rings the bell."); }
}

class Main {
    public static void main(String[] args) {
        Rickshaw r = new Rickshaw("Karim");
        r.move();      // inherited from Vehicle
        r.ringBell();  // defined in Rickshaw
    }
}
super(...) must come first. The first statement in a subclass constructor must be a call to a parent constructor — either explicit super(...) or an implicit no-arg call. Without it, the parent's initialisation would be skipped.

3. Object — The Mother of All Classes

Every class you ever write ultimately extends java.lang.Object. If you do not say extends X, the compiler silently inserts extends Object. That is why every object already has toString(), equals(), hashCode(), and getClass() — they are inherited from Object.

আপনি যা-ই লিখুন, শেষমেশ প্রতিটি class java.lang.Object-এর উত্তরসূরি। তাই প্রতিটি object-এর কাছেই toString(), equals(), hashCode() ইত্যাদি method পাওয়া যায় — এগুলো Object-এর উপহার।
Object Vehicle BankAccount Rickshaw CNG SavingsAccount Figure 14.1 — Java-তে সব class-ই শেষ পর্যন্ত Object থেকে উত্তরাধিকারসূত্রে পাওয়া।

4. super.method() — Calling Up the Chain

A subclass may override a parent method (replace its implementation) but still want the parent's behaviour as part of the new one. Use super.methodName(...) to reach the parent's version.

Main.java
class BankAccount {
    protected double balance;
    BankAccount(double opening) { balance = opening; }
    void deposit(double a) { balance += a; System.out.println("Deposited " + a); }
}

class SavingsAccount extends BankAccount {
    double interestRate;
    SavingsAccount(double opening, double rate) {
        super(opening);
        this.interestRate = rate;
    }
    void deposit(double a) {
        super.deposit(a);      // run parent's behaviour
        double bonus = a * 0.01;
        balance += bonus;
        System.out.println("Savings bonus: " + bonus);
    }
}

class Main {
    public static void main(String[] args) {
        SavingsAccount s = new SavingsAccount(1000, 0.05);
        s.deposit(500);
        System.out.println("Final balance: " + s.balance);
    }
}

5. Prefer Composition Over Inheritance

Inheritance is powerful but brittle: subclasses inherit everything, including unwanted methods and implementation details. Change the parent and every subclass can break silently. For most relationships, composition (your class has another object as a field) gives the same reuse with less coupling. Joshua Bloch's famous advice from Effective Java:

"Favor composition over inheritance."
Inheritance শক্তিশালী কিন্তু ভঙ্গুর — subclass সব কিছু, অপ্রয়োজনীয় method সহ, উত্তরাধিকারে পায়। Parent বদলালে subclass চুপচাপ ভেঙে পড়তে পারে। বেশিরভাগ ক্ষেত্রে composition (আপনার class অন্য object-কে field হিসেবে রাখে) একই reuse দেয় অনেক কম coupling-এ। Joshua Bloch-এর বিখ্যাত পরামর্শ — "Favor composition over inheritance।"

✅ When inheritance fits

  • True is-a: Student extends Person.
  • You control both parent & child.
  • Parent is designed for extension (documented).

⚠️ When composition is better

  • Sharing one small behaviour, not a whole identity.
  • Parent is not yours to evolve safely.
  • Relationship is has-a, not is-a.

6. Vocabulary (শব্দভাণ্ডার)

TermMeaningবাংলায়
extendsDeclares that a class inherits from another.এক class অন্যটি থেকে উত্তরাধিকার নিচ্ছে।
Superclass / ParentThe class being inherited from.যে class থেকে উত্তরাধিকার নেওয়া হচ্ছে।
Subclass / ChildThe inheriting class.যে class উত্তরাধিকার নিচ্ছে।
super(...)Call to the parent constructor.Parent-এর constructor-এ কল।
super.m()Call to the parent's version of a method.Parent-এর method-এর সংস্করণ ডাকা।
OverrideRedefine a parent method in a subclass.Subclass-এ parent method পুনঃসংজ্ঞায়ন।
CompositionHas-a relationship: your class holds another object.has-a সম্পর্ক — আপনার class অন্য object ধরে রাখে।

7. Practice Problems

  1. Build Animal (with speak()) and Dog extends Animal that overrides speak(). Create one Dog and call speak().
    Animal class বানান (যার speak() আছে), তারপর Dog extends Animal যেটি speak() override করে। একটি Dog বানিয়ে speak() কল করুন।
    ✨ Show Answer
    Main.java
    class Animal {
        void speak() { System.out.println("Some generic sound"); }
    }
    class Dog extends Animal {
        void speak() { System.out.println("Ghew ghew!"); }
    }
    class Main {
        public static void main(String[] args) {
            new Dog().speak();
        }
    }
  2. Write a class Employee with fields name, salary. Then Manager extends Employee with an extra bonus. Use super(...).
    Employee (name, salary) থেকে Manager উত্তরাধিকার নেবে, Manager-এ অতিরিক্ত bonus। super(...) ব্যবহার করুন।
    ✨ Show Answer
    Main.java
    class Employee {
        String name; double salary;
        Employee(String n, double s) { name = n; salary = s; }
        double pay() { return salary; }
    }
    class Manager extends Employee {
        double bonus;
        Manager(String n, double s, double b) {
            super(n, s);
            bonus = b;
        }
        double pay() { return super.pay() + bonus; }
    }
    class Main {
        public static void main(String[] args) {
            Manager m = new Manager("Habib", 60000, 15000);
            System.out.println(m.name + " earns " + m.pay());
        }
    }
  3. Why does Java forbid multiple class inheritance? Explain in 2–3 sentences with the "diamond problem".
    Java multiple class inheritance কেন নিষিদ্ধ — "diamond problem" দিয়ে দুই-তিন বাক্যে ব্যাখ্যা।
    ✨ Show Answer

    Answer: If class D extended both B and C, and both B and C extended A and overrode the same method, the compiler would not know which overridden version D inherits — this ambiguity is called the diamond problem. Java sidesteps it by allowing only one direct superclass (interfaces with default methods are allowed in multiples, but their rules resolve conflicts explicitly).

    D যদি B ও C দুটো থেকেই উত্তরাধিকার নিত (এবং দুটোর মূল parent এক), একই method-এর কোন version পাবে তা ambiguous হতো — এটাই diamond problem। Java তাই single class inheritance-এ সীমাবদ্ধ।

  4. Design Shape with a method area() returning 0. Then Square extends Shape overriding area(). Print area of a 4×4 square.
    Shape (area() → 0) থেকে Square উত্তরাধিকার নেবে ও area() override করবে। 4×4 Square-এর area print করুন।
    ✨ Show Answer
    Main.java
    class Shape {
        double area() { return 0; }
    }
    class Square extends Shape {
        double side;
        Square(double s) { side = s; }
        double area() { return side * side; }
    }
    class Main {
        public static void main(String[] args) {
            Shape sh = new Square(4);
            System.out.println("Area = " + sh.area());
        }
    }
  5. Give one real-world example where composition is clearly better than inheritance, and justify briefly.
    বাস্তব একটি উদাহরণ দিন যেখানে inheritance-এর চেয়ে composition স্পষ্টতই ভালো — সংক্ষেপে যুক্তি দিন।
    ✨ Show Answer

    Answer: A Car should have an Engine, not extend one. A car is not a kind of engine; it contains an engine alongside wheels, seats, and a gearbox. Composition here lets us swap engine types (petrol, electric, hybrid) at runtime without reshaping the class hierarchy — something single inheritance would make painful.

    Car-এর ভেতরে Engine থাকা উচিত, Car কখনো engine-এর ধরন নয়। Composition-এ petrol/electric/hybrid engine runtime-এ বদলানো যায়, inheritance-এ সেটা কঠিন।

Summary — Module 14

Inheritance models the is-a relationship. A subclass extends exactly one superclass via extends, inherits its fields and methods, and must chain to a parent constructor using super(...) as its first statement. super.method() reaches the parent's version of an overridden method. Every Java class ultimately extends Object, the root of the hierarchy. Inheritance is powerful but tightly couples subclasses to their parents — prefer composition whenever the relationship is has-a rather than is-a.

Inheritance is-a সম্পর্ককে প্রকাশ করে। extends দিয়ে একটি parent থেকে subclass উত্তরাধিকার নেয়, super(...) constructor-এর প্রথমে parent-কে ডাকে, super.method() parent-এর version-কে। সব Java class শেষ পর্যন্ত Object থেকে এসেছে। সম্পর্কটি has-a হলে composition বেছে নিন।

Next Module → Polymorphism ও Dynamic Dispatch — overridden method runtime-এ কীভাবে বেছে নেওয়া হয়।