☕ Java

Inheritance in Java

Inheritance lets you build new classes on top of existing ones — reusing code instead of rewriting it. If a SavingsAccount IS-A BankAccount, why define all the BankAccount stuff twice? Inherit it.

Why Inheritance Exists

Real-world example: Think of employees at a company. Every employee has a name, salary, and an ID. But a Manager also has a team size and a budget. A Developer has a tech stack and project assignments. Instead of creating three completely separate classes that all repeat the name/salary/ID fields, you create one Employee class with the common stuff, and then Manager and Developer extend it — inheriting everything and adding only what's unique to them. This is the "Don't Repeat Yourself" (DRY) principle in action. Key rules: • Use the extends keyword to inherit from a class • Java only supports single inheritance — a class can extend only ONE parent • Use super() to call the parent's constructor

Inheritance in Code

Java
// Parent class (Superclass)
class Animal {
    String name;

    public Animal(String name) {
        this.name = name;
    }

    public void eat() {
        System.out.println(name + " is eating.");
    }

    public void sleep() {
        System.out.println(name + " is sleeping.");
    }
}

// Child class (Subclass) — inherits eat() and sleep() from Animal
class Dog extends Animal {

    public Dog(String name) {
        super(name);  // calls Animal's constructor — required!
    }

    // Dog's own method
    public void bark() {
        System.out.println(name + " says: Woof!");
    }
}

// Usage
Dog dog = new Dog("Rex");
dog.eat();    // Inherited from Animal: "Rex is eating."
dog.sleep();  // Inherited from Animal: "Rex is sleeping."
dog.bark();   // Dog's own method: "Rex says: Woof!"

Method Overriding — Changing Inherited Behavior

Inheritance gives you the parent's methods. But what if the child needs different behavior? Override it. The @Override annotation is optional but strongly recommended — it tells the compiler "I'm intentionally overriding a parent method", and it'll warn you if you make a typo in the method signature.
Java
class Animal {
    public void sound() {
        System.out.println("Some generic animal sound");
    }
}

class Dog extends Animal {
    @Override
    public void sound() {
        System.out.println("Woof!");
    }
}

class Cat extends Animal {
    @Override
    public void sound() {
        System.out.println("Meow!");
    }
}

// Each subclass has its own version of sound()
Animal a = new Dog();
a.sound();  // Woof! — Java calls Dog's version, not Animal's