Monday, July 21, 2025

Java Inheritance

# Java Inheritance: Complete Guide with Examples

Inheritance is one of the fundamental concepts of object-oriented programming (OOP) in Java. It allows a class to inherit properties and behaviors (fields and methods) from another class.

## Basic Inheritance Syntax

```java
class ParentClass {
    // fields and methods
}

class ChildClass extends ParentClass {
    // additional fields and methods
}
```

## Key Concepts of Inheritance

### 1. Single Inheritance
Java supports single inheritance (a class can extend only one parent class).

```java
class Animal {
    void eat() {
        System.out.println("Eating...");
    }
}

class Dog extends Animal {
    void bark() {
        System.out.println("Barking...");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog d = new Dog();
        d.eat();  // Inherited from Animal
        d.bark(); // Defined in Dog
    }
}
```

### 2. Multilevel Inheritance
A class can inherit from another class which itself inherits from another class.

```java
class Animal {
    void eat() {
        System.out.println("Eating...");
    }
}

class Dog extends Animal {
    void bark() {
        System.out.println("Barking...");
    }
}

class Puppy extends Dog {
    void weep() {
        System.out.println("Weeping...");
    }
}

public class Main {
    public static void main(String[] args) {
        Puppy p = new Puppy();
        p.eat();  // From Animal
        p.bark(); // From Dog
        p.weep(); // From Puppy
    }
}
```

### 3. Hierarchical Inheritance
Multiple classes inherit from a single parent class.

```java
class Animal {
    void eat() {
        System.out.println("Eating...");
    }
}

class Dog extends Animal {
    void bark() {
        System.out.println("Barking...");
    }
}

class Cat extends Animal {
    void meow() {
        System.out.println("Meowing...");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog d = new Dog();
        d.eat();  // From Animal
        d.bark(); // From Dog
        
        Cat c = new Cat();
        c.eat();  // From Animal
        c.meow(); // From Cat
    }
}
```

### 4. Method Overriding
Child class can provide its own implementation of a method that is already defined in its parent class.

```java
class Animal {
    void makeSound() {
        System.out.println("Animal makes a sound");
    }
}

class Dog extends Animal {
    @Override
    void makeSound() {
        System.out.println("Dog barks");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal a = new Animal();
        a.makeSound(); // Output: Animal makes a sound
        
        Dog d = new Dog();
        d.makeSound(); // Output: Dog barks
    }
}
```

### 5. The `super` Keyword
Used to refer to immediate parent class instance variable, method, or constructor.

```java
class Vehicle {
    int maxSpeed = 120;
}

class Car extends Vehicle {
    int maxSpeed = 180;
    
    void display() {
        System.out.println("Maximum Speed: " + super.maxSpeed); // Parent class
        System.out.println("Maximum Speed: " + maxSpeed);       // Current class
    }
}

public class Main {
    public static void main(String[] args) {
        Car c = new Car();
        c.display();
    }
}
```

### 6. Inheritance with Constructors
Parent class constructor is called before child class constructor.

```java
class Parent {
    Parent() {
        System.out.println("Parent constructor");
    }
}

class Child extends Parent {
    Child() {
        super(); // Implicitly called if not written
        System.out.println("Child constructor");
    }
}

public class Main {
    public static void main(String[] args) {
        Child c = new Child();
    }
}
```

### 7. `final` Keyword and Inheritance
- `final` class cannot be inherited
- `final` method cannot be overridden

```java
final class FinalClass {
    // Cannot be inherited
}

class Parent {
    final void display() {
        System.out.println("This cannot be overridden");
    }
}

class Child extends Parent {
    // This would cause a compile error:
    // void display() { System.out.println("Trying to override"); }
}
```

## When to Use Inheritance

1. **IS-A relationship**: When a class "is a" specialized version of another class
   - Dog IS-A Animal
   - Car IS-A Vehicle

2. **Code reusability**: When you want to reuse existing code with additional features

3. **Polymorphism**: When you need to implement runtime polymorphism through method overriding

## Important Points

1. Java doesn't support multiple inheritance with classes (but supports with interfaces)
2. Private members are not inherited
3. Constructors are not inherited
4. All classes in Java implicitly inherit from `Object` class
5. Use `@Override` annotation to explicitly indicate method overriding

## Practical Example: Employee Management System

```java
class Employee {
    private String name;
    private double salary;
    
    public Employee(String name, double salary) {
        this.name = name;
        this.salary = salary;
    }
    
    public void displayDetails() {
        System.out.println("Name: " + name);
        System.out.println("Salary: $" + salary);
    }
    
    public double calculateBonus() {
        return salary * 0.05; // 5% bonus
    }
}

class Manager extends Employee {
    private String department;
    
    public Manager(String name, double salary, String department) {
        super(name, salary);
        this.department = department;
    }
    
    @Override
    public void displayDetails() {
        super.displayDetails();
        System.out.println("Department: " + department);
    }
    
    @Override
    public double calculateBonus() {
        return super.calculateBonus() + 1000; // Extra $1000 for managers
    }
}

public class Main {
    public static void main(String[] args) {
        Employee emp = new Employee("John Doe", 50000);
        Manager mgr = new Manager("Jane Smith", 80000, "IT");
        
        emp.displayDetails();
        System.out.println("Bonus: $" + emp.calculateBonus());
        
        System.out.println();
        
        mgr.displayDetails();
        System.out.println("Bonus: $" + mgr.calculateBonus());
    }
}
```

This example demonstrates how inheritance allows us to extend the basic `Employee` class to create a specialized `Manager` class with additional properties and behaviors while reusing existing code.

No comments: