Inheritance in Java

Loading

Inheritance in Java is a mechanism that allows one class to inherit the properties (fields) and behaviors (methods) of another class. It promotes code reusability and establishes a relationship between classes. The class that inherits is called the subclass (or child class), and the class being inherited from is called the superclass (or parent class). Inheritance is one of the four pillars of Object-Oriented Programming (OOP).


1. Syntax of Inheritance

In Java, inheritance is achieved using the extends keyword.

class Superclass {
    // Fields and methods
}

class Subclass extends Superclass {
    // Additional fields and methods
}

2. Types of Inheritance

a. Single Inheritance

  • A subclass inherits from one superclass.
  • Java supports single inheritance for classes (a class can extend only one class). Example:
   class Animal {
       void eat() {
           System.out.println("This animal eats food.");
       }
   }

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

   public class Main {
       public static void main(String[] args) {
           Dog dog = new Dog();
           dog.eat(); // Inherited method
           dog.bark(); // Subclass method
       }
   }

b. Multilevel Inheritance

  • A subclass inherits from a superclass, which in turn inherits from another superclass. Example:
   class Animal {
       void eat() {
           System.out.println("This animal eats food.");
       }
   }

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

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

   public class Main {
       public static void main(String[] args) {
           Puppy puppy = new Puppy();
           puppy.eat();  // Inherited from Animal
           puppy.bark(); // Inherited from Dog
           puppy.weep(); // Subclass method
       }
   }

c. Hierarchical Inheritance

  • Multiple subclasses inherit from a single superclass. Example:
   class Animal {
       void eat() {
           System.out.println("This animal eats food.");
       }
   }

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

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

   public class Main {
       public static void main(String[] args) {
           Dog dog = new Dog();
           dog.eat(); // Inherited from Animal
           dog.bark(); // Subclass method

           Cat cat = new Cat();
           cat.eat(); // Inherited from Animal
           cat.meow(); // Subclass method
       }
   }

d. Multiple Inheritance (Not Supported in Java)

  • A subclass inherits from more than one superclass.
  • Java does not support multiple inheritance for classes to avoid complexity and ambiguity (e.g., the “diamond problem”).
  • However, multiple inheritance can be achieved using interfaces.

3. Key Concepts in Inheritance

a. super Keyword

  • Used to refer to the superclass (parent class).
  • Can be used to:
    • Call the superclass constructor.
    • Access superclass fields and methods.
    Example:
   class Animal {
       String name;

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

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

   class Dog extends Animal {
       Dog(String name) {
           super(name); // Call superclass constructor
       }

       void bark() {
           System.out.println(name + " is barking.");
       }
   }

b. Method Overriding

  • A subclass can provide a specific implementation of a method that is already defined in its superclass.
  • The method in the subclass must have the same name, return type, and parameters as the method in the superclass. Example:
   class Animal {
       void sound() {
           System.out.println("Animal makes a sound");
       }
   }

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

   public class Main {
       public static void main(String[] args) {
           Animal myDog = new Dog(); // Upcasting
           myDog.sound(); // Calls the overridden method in Dog class
       }
   }

c. Access Modifiers in Inheritance

  • public: Accessible everywhere.
  • protected: Accessible within the same package and subclasses.
  • private: Not accessible in subclasses.
  • Default (no modifier): Accessible within the same package.

d. Final Classes and Methods

  • A final class cannot be inherited.
  • A final method cannot be overridden. Example:
   final class Animal {
       final void sound() {
           System.out.println("Animal makes a sound");
       }
   }

   // class Dog extends Animal { } // Error: Cannot inherit from final class

4. Example Program

// Superclass
class Vehicle {
    String brand;

    Vehicle(String brand) {
        this.brand = brand;
    }

    void start() {
        System.out.println(brand + " is starting.");
    }
}

// Subclass
class Car extends Vehicle {
    int wheels;

    Car(String brand, int wheels) {
        super(brand); // Call superclass constructor
        this.wheels = wheels;
    }

    void drive() {
        System.out.println(brand + " with " + wheels + " wheels is driving.");
    }
}

public class Main {
    public static void main(String[] args) {
        Car car = new Car("Toyota", 4);
        car.start(); // Inherited method
        car.drive(); // Subclass method
    }
}

5. Advantages of Inheritance

  1. Code Reusability: Reuse fields and methods of an existing class.
  2. Code Organization: Improves code structure and readability.
  3. Polymorphism: Enables runtime polymorphism through method overriding.
  4. Extensibility: Easily extend the functionality of existing classes.

Summary

ConceptDescription
Single InheritanceA subclass inherits from one superclass.
Multilevel InheritanceA subclass inherits from a superclass, which in turn inherits from another.
Hierarchical InheritanceMultiple subclasses inherit from a single superclass.
super KeywordRefers to the superclass (used to call constructors, fields, and methods).
Method OverridingA subclass provides a specific implementation of a superclass method.
Access ModifiersControl the visibility of fields and methods in inheritance.
Final Classes/MethodsPrevent inheritance and method overriding.

Inheritance is a powerful feature of Java that promotes code reuse and establishes relationships between classes. Understanding its concepts and usage is essential for effective object-oriented programming.

Leave a Reply

Your email address will not be published. Required fields are marked *