Popular Searches
Popular Course Categories
Popular Courses

Introduction to Inheritance in Java

Introduction to Inheritance in Java

Encapsulation, Inheritance, and Polymorphism

Introduction to Inheritance in Java

Course: Core Java Training

Topic: Introduction to Inheritance in Java

Course Link: Core Java Training Course

Demo Link: Register for a Course Demo

Website: JustAcademy


1. Introduction to Inheritance

Inheritance is one of the fundamental concepts of object-oriented programming (OOP) in Java. It allows one class to acquire accessible fields and methods from another class. Instead of writing the same functionality repeatedly, developers can define common behavior in a parent class and extend it in child classes.

For example, a general Vehicle class may contain common properties such as brand and speed, along with methods such as start() and stop(). Classes such as Car, Bike, and Truck can extend Vehicle and add their own specialized properties and behavior.

Inheritance promotes code reuse, reduces duplication, supports method overriding, and helps establish relationships between related classes. Java's inheritance documentation explains how subclasses build upon existing classes.

2. Learning Objectives

  • Understand the meaning and purpose of inheritance in Java.
  • Learn the roles of parent classes and child classes.
  • Understand the extends keyword and inheritance syntax.
  • Learn how inherited methods and accessible fields can be reused.
  • Explore the major forms of class inheritance.
  • Understand constructors and the super keyword in inheritance.
  • Learn method overriding and its relationship to polymorphism.
  • Identify the limitations and best practices of inheritance.

3. What Is Inheritance in Java?

Inheritance is a mechanism through which a class derives from another class. The derived class can reuse accessible behavior from the existing class and define additional features of its own.

Java uses the extends keyword to establish inheritance between classes.

Important Terminology

Term Meaning
Superclass The parent or base class from which another class derives.
Subclass The child or derived class that extends another class.
Inheritance The mechanism that allows a subclass to reuse accessible members and specialize behavior.
extends The keyword used to declare that a class inherits from another class.
super A keyword used to refer to superclass members or invoke a superclass constructor.
Method overriding A subclass provides a compatible implementation of an inherited instance method.
Code reusability The ability to use existing functionality without unnecessarily rewriting it.

4. Basic Syntax of Inheritance

The general syntax for creating a subclass is:

class ParentClass {
    // Common fields and methods
}

class ChildClass extends ParentClass {
    // Additional fields and methods
}

In this structure, ChildClass extends ParentClass. The child class can use accessible inherited members and add new fields and methods.

5. First Inheritance Example

Consider a program in which an Animal class defines a common method and a Dog class inherits that method.

class Animal {
    void eat() {
        System.out.println("Animal is eating");
    }
}

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

public class InheritanceDemo {
    public static void main(String[] args) {
        Dog dog = new Dog();

        dog.eat();
        dog.bark();
    }
}

Output

Animal is eating
Dog is barking

Explanation

  • Animal is the superclass.
  • Dog is the subclass because it extends Animal.
  • The eat() method is inherited from Animal.
  • The bark() method is defined directly in Dog.
  • The Dog object can call both methods because they are accessible.

6. Why Is Inheritance Used?

Inheritance is useful when multiple classes share common characteristics but also need specialized behavior.

  • Code reuse: Common fields and methods can be defined once in a superclass.
  • Reduced duplication: Similar classes do not need to repeat the same implementation.
  • Extensibility: Subclasses can add specialized fields and methods.
  • Maintainability: Shared behavior can be updated centrally when the class design supports it.
  • Polymorphism: Subclass objects can be used through suitable superclass references.
  • Logical relationships: Inheritance models an appropriate “is-a” relationship between types.

7. Understanding the Parent Class

A parent class contains the common fields and methods that related subclasses can reuse. It provides the shared foundation for the class hierarchy.

Example

class Vehicle {
    String brand;
    int speed;

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

    void stop() {
        System.out.println("Vehicle is stopping");
    }
}

The Vehicle class defines two fields and two methods. Different vehicle subclasses can inherit these features instead of implementing them independently.

8. Understanding the Child Class

A child class extends a parent class and can add its own properties and behavior. It can also override eligible inherited instance methods to provide specialized implementations.

Example

class Car extends Vehicle {
    int numberOfDoors;

    void playMusic() {
        System.out.println("Car music system is playing");
    }
}

The Car class inherits the accessible members of Vehicle and adds the numberOfDoors field and playMusic() method.

9. Complete Example: Vehicle Inheritance

class Vehicle {
    String brand;
    int speed;

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

    void displaySpeed() {
        System.out.println("Speed: " + speed + " km/h");
    }
}

class Car extends Vehicle {
    int numberOfDoors;

    void displayCarDetails() {
        System.out.println("Brand: " + brand);
        System.out.println("Doors: " + numberOfDoors);
    }
}

public class VehicleDemo {
    public static void main(String[] args) {
        Car car = new Car();

        car.brand = "Toyota";
        car.speed = 80;
        car.numberOfDoors = 4;

        car.start();
        car.displaySpeed();
        car.displayCarDetails();
    }
}

Output

Toyota is starting
Speed: 80 km/h
Brand: Toyota
Doors: 4

Explanation: The Car object can use the accessible brand and speed fields and the start() and displaySpeed() methods inherited from Vehicle. It also uses its own numberOfDoors field and displayCarDetails() method.

10. Types of Inheritance in Java

Inheritance structures are commonly described using five patterns: single, multilevel, hierarchical, multiple, and hybrid inheritance. Java supports single, multilevel, and hierarchical inheritance through classes. Multiple inheritance of classes is not supported, but Java allows a class to implement multiple interfaces.

Type Description Class Support in Java
Single inheritance One child class extends one parent class. Supported
Multilevel inheritance A class extends a class that already extends another class. Supported
Hierarchical inheritance Multiple child classes extend the same parent class. Supported
Multiple inheritance One class inherits from multiple classes. Not supported for classes; multiple interfaces can be implemented.
Hybrid inheritance A combination of inheritance patterns. Possible through supported class inheritance and interfaces, but not through multiple class inheritance.

11. Single Inheritance

Single inheritance occurs when one subclass extends one superclass. It is the simplest form of class inheritance in Java.

Structure

Animal
   |
   v
  Dog

Example

class Animal {
    void eat() {
        System.out.println("Animal eats food");
    }
}

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

public class SingleInheritanceDemo {
    public static void main(String[] args) {
        Dog dog = new Dog();

        dog.eat();
        dog.bark();
    }
}

Output

Animal eats food
Dog barks

Explanation: The Dog class directly extends Animal. It inherits the accessible eat() method and defines its own bark() method.

12. Multilevel Inheritance

Multilevel inheritance occurs when a class extends a subclass, creating a chain of inheritance across multiple levels.

Structure

Animal
   |
   v
  Dog
   |
   v
Puppy

Example

class Animal {
    void eat() {
        System.out.println("Animal eats");
    }
}

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

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

public class MultilevelDemo {
    public static void main(String[] args) {
        Puppy puppy = new Puppy();

        puppy.eat();
        puppy.bark();
        puppy.weep();
    }
}

Output

Animal eats
Dog barks
Puppy weeps

Explanation: Puppy extends Dog, and Dog extends Animal. The puppy can use accessible methods declared at all levels of the inheritance chain.

13. Hierarchical Inheritance

Hierarchical inheritance occurs when multiple subclasses extend the same superclass. Each child class can reuse common behavior while adding its own specialized functionality.

Structure

        Vehicle
        /     \
       v       v
      Car     Bike

Example

class Vehicle {
    void start() {
        System.out.println("Vehicle starts");
    }
}

class Car extends Vehicle {
    void drive() {
        System.out.println("Car is driving");
    }
}

class Bike extends Vehicle {
    void ride() {
        System.out.println("Bike is being ridden");
    }
}

public class HierarchicalDemo {
    public static void main(String[] args) {
        Car car = new Car();
        Bike bike = new Bike();

        car.start();
        car.drive();

        bike.start();
        bike.ride();
    }
}

Output

Vehicle starts
Car is driving
Vehicle starts
Bike is being ridden

Explanation: Both Car and Bike inherit the start() method from Vehicle. Each subclass provides a separate method for its specialized behavior.

14. Multiple Inheritance and Interfaces

Java does not allow a class to extend two or more classes directly. For example, the declaration class C extends A, B is invalid Java syntax.

Java supports a class implementing multiple interfaces. This allows a class to provide behavior for several type contracts without inheriting implementation from multiple classes.

Example

interface Printable {
    void print();
}

interface Showable {
    void show();
}

class Report implements Printable, Showable {
    public void print() {
        System.out.println("Printing report");
    }

    public void show() {
        System.out.println("Displaying report");
    }
}

public class InterfaceInheritanceDemo {
    public static void main(String[] args) {
        Report report = new Report();

        report.print();
        report.show();
    }
}

Output

Printing report
Displaying report

Explanation: The Report class implements both Printable and Showable. It supplies implementations of both interface methods.

15. Hybrid Inheritance

Hybrid inheritance combines two or more inheritance patterns. Java cannot create hybrid inheritance by extending multiple classes, but class inheritance can be combined with multiple interfaces.

Example

class Device {
    void powerOn() {
        System.out.println("Device powered on");
    }
}

interface Camera {
    void takePhoto();
}

interface MusicPlayer {
    void playMusic();
}

class Smartphone extends Device implements Camera, MusicPlayer {
    public void takePhoto() {
        System.out.println("Photo captured");
    }

    public void playMusic() {
        System.out.println("Music playing");
    }
}

public class HybridDemo {
    public static void main(String[] args) {
        Smartphone phone = new Smartphone();

        phone.powerOn();
        phone.takePhoto();
        phone.playMusic();
    }
}

Output

Device powered on
Photo captured
Music playing

Explanation: Smartphone extends one class, Device, and implements two interfaces. This combines class inheritance with multiple interface contracts.

16. The super Keyword in Java

The super keyword is used in a subclass to refer to its immediate superclass. It is commonly used to invoke a superclass constructor or access an accessible superclass method or field that is hidden by a subclass member.

Uses of super

  • Call a superclass constructor using super() or super(arguments).
  • Call an accessible superclass method using super.methodName().
  • Refer to an accessible superclass field using super.fieldName when a subclass field hides it.

Example: Calling a Parent Constructor

class Person {
    String name;

    Person(String name) {
        this.name = name;
        System.out.println("Person constructor executed");
    }
}

class Student extends Person {
    int rollNumber;

    Student(String name, int rollNumber) {
        super(name);
        this.rollNumber = rollNumber;
        System.out.println("Student constructor executed");
    }

    void display() {
        System.out.println("Name: " + name);
        System.out.println("Roll Number: " + rollNumber);
    }
}

public class SuperDemo {
    public static void main(String[] args) {
        Student student = new Student("Meera", 101);
        student.display();
    }
}

Output

Person constructor executed
Student constructor executed
Name: Meera
Roll Number: 101

Explanation: The Student constructor calls super(name) to initialize the inherited name field through the Person constructor. The student-specific roll number is then initialized.

17. Constructor Behavior in Inheritance

Constructors are not inherited by subclasses. However, a subclass constructor can invoke a superclass constructor using super() or super(arguments).

  • If a constructor does not explicitly invoke another constructor, Java ordinarily inserts an implicit no-argument superclass constructor invocation when permitted.
  • If the superclass has no accessible no-argument constructor, the subclass must explicitly invoke an appropriate superclass constructor.
  • The superclass constructor chain executes before the subclass completes its own instance initialization and constructor body.
  • A constructor invocation using this() or super() must follow Java's constructor-invocation rules.

18. Method Overriding in Inheritance

Method overriding occurs when a subclass provides a compatible implementation of an inherited instance method. The subclass method must have an appropriate signature and must not reduce the visibility of the overridden method.

Overriding allows a subclass to customize inherited behavior. The @Override annotation is recommended because the compiler checks that the method actually overrides or implements a compatible method.

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 OverridingDemo {
    public static void main(String[] args) {
        Animal animal = new Animal();
        Dog dog = new Dog();

        animal.sound();
        dog.sound();
    }
}

Output

Animal makes a sound
Dog barks

Explanation: The Dog class overrides the inherited sound() method to provide behavior specific to dogs.

19. Inheritance and Polymorphism

Polymorphism allows a superclass reference to refer to an object of a subclass. When an overridden instance method is called through that reference, Java selects the implementation based on the actual object's runtime class.

Example

class Animal {
    void sound() {
        System.out.println("Animal sound");
    }
}

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

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

public class PolymorphismDemo {
    public static void main(String[] args) {
        Animal animal1 = new Cat();
        Animal animal2 = new Dog();

        animal1.sound();
        animal2.sound();
    }
}

Output

Cat meows
Dog barks

Explanation: Both variables are declared as Animal references, but they point to different subclass objects. Java calls the overridden method belonging to each object's runtime class.

20. Access Modifiers and Inheritance

Access modifiers determine which superclass members a subclass can access. Inheritance does not make every field or method directly accessible.

Access Level Access by Subclass in Same Package Access by Subclass in Another Package
public Yes Yes, if the declaring type is accessible
protected Yes Yes, subject to protected-access rules
Package-private Yes No direct access solely by inheritance
private No direct access No direct access

A subclass does not directly inherit or access private superclass fields and methods as ordinary inherited members. It can use public or protected superclass methods that provide controlled access to private state.

21. The Object Class in Java

Object, from the java.lang package, is the root superclass of Java classes. A class that does not explicitly extend another class implicitly extends Object.

The Object class provides commonly used methods such as:

  • toString() — returns a string representation of an object.
  • equals(Object obj) — compares objects according to the method's implementation.
  • hashCode() — returns a hash code value.
  • getClass() — returns the runtime class of an object.
  • wait(), notify(), and notifyAll() — support thread coordination when used according to their synchronization requirements.

22. Advantages of Inheritance

  • Reusability: Common functionality can be shared through a superclass.
  • Reduced duplication: Shared code does not need to be rewritten in every subclass.
  • Extensibility: New subclasses can add specialized features.
  • Polymorphism: Related objects can be handled through a common superclass type.
  • Maintainability: Shared behavior can be maintained centrally when the hierarchy is well designed.
  • Clear type relationships: A well-designed hierarchy communicates which classes are specialized forms of another class.

23. Limitations of Inheritance

  • Tight coupling: A subclass depends on the behavior and design of its superclass.
  • Limited class inheritance: A Java class can directly extend only one class.
  • Complex hierarchies: Deep inheritance chains can make behavior difficult to understand.
  • Fragile base class: Changes to a superclass can unintentionally affect subclasses.
  • Incorrect relationships: Inheritance is unsuitable when the relationship is not genuinely an “is-a” relationship.
  • Encapsulation concerns: Exposing too many protected members can make it harder to change a superclass safely.

24. Inheritance vs. Composition

Inheritance represents an “is-a” relationship, while composition represents a “has-a” relationship. Composition means that a class contains or uses an object of another class instead of deriving from it.

Feature Inheritance Composition
Relationship Is-a Has-a
Implementation Uses extends for class inheritance Stores or uses another object
Code reuse Reuses accessible inherited behavior Reuses behavior by delegation to a contained object
Coupling Can create tighter coupling to the superclass Can provide more flexible component replacement
Example Dog extends Animal Car contains an Engine

Use inheritance when the subclass is genuinely a specialized form of the parent class. Prefer composition when a class mainly needs to use another object's functionality.

25. Common Mistakes When Using Inheritance

  • Using inheritance only to reuse code when the relationship is not an appropriate “is-a” relationship.
  • Assuming private superclass fields are directly accessible in a subclass.
  • Trying to extend multiple classes in one class declaration.
  • Forgetting to invoke the appropriate superclass constructor when no accessible no-argument constructor exists.
  • Overriding a method with an incompatible signature or reduced visibility.
  • Confusing method overriding with method overloading.
  • Creating unnecessarily deep inheritance hierarchies.
  • Changing superclass behavior without considering its effects on subclasses.
  • Forgetting the @Override annotation when overriding an inherited method.
  • Making superclass fields public when protected methods or controlled access would be more appropriate.

26. Best Practices for Inheritance

  • Use inheritance only when there is a clear “is-a” relationship.
  • Place common behavior in a superclass only when it is genuinely shared.
  • Keep inheritance hierarchies as simple as possible.
  • Use @Override to make overriding intentions explicit.
  • Keep fields private where practical and expose behavior through suitable methods.
  • Use super() to initialize superclass state correctly.
  • Avoid changing the expected behavior of inherited methods in surprising ways.
  • Prefer composition when the relationship is “has-a” or when components need to be replaceable.
  • Write tests for both superclass behavior and subclass-specific behavior.
  • Document important assumptions that subclasses must follow.

27. Practice Exercises

  1. Create a class named Person with fields for name and age. Create a Student subclass with a roll number.
  2. Build a Vehicle superclass and create Car and Bike subclasses.
  3. Demonstrate single inheritance using an Animal and Dog class.
  4. Demonstrate multilevel inheritance using LivingThing, Animal, and Dog.
  5. Demonstrate hierarchical inheritance with Shape, Circle, and Rectangle.
  6. Create a parent class with a parameterized constructor and invoke it from a child constructor using super().
  7. Override a superclass method in a subclass and demonstrate the use of @Override.
  8. Use a superclass reference to call overridden methods on two different subclass objects.
  9. Implement two interfaces in one class to demonstrate multiple interface implementation.
  10. Create a class that contains an object of another class and compare the design with an inheritance-based approach.

28. Interview Questions and Answers

Q1. What is inheritance in Java?

Inheritance is an OOP mechanism that allows a class to derive from another class, reusing accessible members and adding specialized behavior.

Q2. Which keyword is used for class inheritance?

The extends keyword is used to declare that a class extends another class.

Q3. What is a superclass?

A superclass is the parent or base class from which another class derives.

Q4. What is a subclass?

A subclass is a child or derived class that extends a superclass.

Q5. Does Java support multiple inheritance through classes?

No. A class can extend only one direct superclass. Java does allow a class to implement multiple interfaces.

Q6. What is single inheritance?

Single inheritance occurs when one subclass extends one superclass.

Q7. What is multilevel inheritance?

Multilevel inheritance occurs when a class extends a subclass that itself extends another class, forming an inheritance chain.

Q8. What is hierarchical inheritance?

Hierarchical inheritance occurs when multiple subclasses extend the same superclass.

Q9. What is the purpose of the super keyword?

The super keyword can invoke a superclass constructor or access an accessible superclass field or method.

Q10. Are constructors inherited in Java?

No. Constructors are not inherited, but a subclass constructor can invoke a superclass constructor.

Q11. What is method overriding?

Method overriding occurs when a subclass supplies a compatible implementation of an inherited instance method.

Q12. What is the difference between inheritance and polymorphism?

Inheritance establishes relationships between classes and allows member reuse. Polymorphism allows a common type to refer to objects of different compatible types and dispatch overridden instance methods according to the runtime object.

Q13. Can a subclass directly access private members of its superclass?

No. Private members cannot be accessed directly as ordinary inherited members. The subclass can use suitable public or protected methods provided by the superclass.

Q14. What is the difference between inheritance and composition?

Inheritance models an “is-a” relationship, while composition models a “has-a” relationship by using another object as a component.

Q15. Why is the Object class important?

Object is the root superclass of Java classes and provides common methods such as toString(), equals(), and hashCode().

29. Quick Revision Checklist

  • Inheritance is a core concept of object-oriented programming.
  • The extends keyword establishes class inheritance.
  • A superclass provides common behavior; a subclass specializes it.
  • Java supports single, multilevel, and hierarchical class inheritance.
  • Java does not support extending multiple classes directly.
  • A class can implement multiple interfaces.
  • Constructors are not inherited, but superclass constructors can be invoked.
  • The super keyword refers to superclass constructors and accessible members.
  • Method overriding allows subclasses to specialize inherited instance methods.
  • Polymorphism allows superclass references to refer to subclass objects.
  • Private superclass members are not directly accessible in subclasses.
  • Use inheritance for “is-a” relationships and composition for “has-a” relationships.

30. Conclusion

Inheritance is an essential feature of Java that helps developers build reusable, extensible, and logically organized object-oriented programs. By defining common functionality in a superclass and extending it through subclasses, developers can reduce duplication and represent relationships between related types.

Understanding the extends and super keywords, inheritance patterns, constructors, method overriding, and polymorphism provides a strong foundation for advanced Java topics. Always design inheritance hierarchies carefully and use composition when it provides a clearer and more flexible solution.

Continue learning with the JustAcademy Core Java Training Course. You can also register for a course demo or visit the JustAcademy website for more information.

Previous Next
whatsapp