Java Inheritance - Parent and Child Classes in OOP

⏱️ 20 min read • Beginner Level • Lesson 50

Lesson 50 of 124 of Java Tutorial
You have completed this lesson

Completed on . You can revise this lesson or continue to the next topic.

Inheritance in Java is an important object-oriented programming concept where one class can acquire the properties and behaviors of another class. It helps you reuse code, organize classes, and build relationships between objects.

In this lesson, you will learn Java inheritance deeply with the extends keyword, parent and child classes, types of inheritance, constructor execution order, super keyword, method overriding, protected access, upcasting, tricky cases, common mistakes, and interview questions. Before learning inheritance, you should understand Java Class and Objects, Java Class Members, Java Constructors, and Java this Keyword.


What is Inheritance in Java?

Inheritance is a mechanism in Java where one class can use the variables and methods of another class. The class that gives members is called the parent class, and the class that receives members is called the child class.

Simple Meaning: Inheritance means creating a new class from an existing class so that the new class can reuse existing code.
  • Inheritance supports code reusability.
  • Inheritance represents an IS-A relationship.
  • Inheritance is implemented using the extends keyword.
  • A child class can access accessible members of the parent class.
  • Constructors are not inherited, but parent constructors are called during child object creation.

Real-World Analogy

Think about a general Vehicle. A Car is a type of Vehicle, and a Bike is also a type of Vehicle.

        Vehicle
      /         \
    Car         Bike
                  \
                SportsBike
                        

Vehicle

Common features like speed, fuel, start, and stop.

Car

Inherits vehicle features and adds car-specific features.

Bike

Inherits vehicle features and adds bike-specific features.

Remember: A Car is a Vehicle. This is why inheritance is called an IS-A relationship.

Why Use Inheritance?

Inheritance is used when multiple classes share common properties or behavior. Instead of writing the same code again and again, common code is written in a parent class.

Benefit Meaning
Code Reusability Common code can be written once in the parent class and reused by child classes.
Cleaner Design Classes can be arranged in a logical parent-child relationship.
Extensibility Existing code can be extended without modifying the parent class.
Polymorphism Support Inheritance allows method overriding and runtime polymorphism.

Important Terms in Inheritance

Term Meaning
Parent Class The class whose members are inherited. Also called superclass or base class.
Child Class The class that inherits members. Also called subclass or derived class.
extends Keyword used to inherit a class.
super Keyword used to refer to parent class members or constructor.
IS-A Relationship A relationship where child is a specific type of parent.

Syntax of Inheritance in Java

InheritanceSyntax.java
class ParentClass {
    // parent class members
}

class ChildClass extends ParentClass {
    // child class members
}
Important: Java uses the extends keyword to inherit one class from another class.

Basic Inheritance Example

BasicInheritanceExample.java
Copy Try Download
class Animal {
    void eat() {
        System.out.println("Animal eats food");
    }
}

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

    public static void main(String[] args) {
        Dog d = new Dog();
        d.eat();
        d.bark();
    }
}

Output:

Animal eats food
Dog barks

Code Explanation

  1. Animal is the parent class.
  2. Dog is the child class.
  3. Dog extends Animal means Dog inherits Animal.
  4. The Dog object can call both eat() and bark().

Types of Inheritance in Java

Java supports inheritance in different forms. Some are directly supported through classes, and some are achieved through interfaces.

Type Supported with Classes? Meaning
Single Inheritance Yes One child class inherits one parent class.
Multilevel Inheritance Yes A class inherits from a child class, forming a chain.
Hierarchical Inheritance Yes Multiple child classes inherit the same parent class.
Multiple Inheritance No, with classes A class cannot extend multiple classes in Java.
Hybrid Inheritance Through interfaces A combination of inheritance types, usually achieved using interfaces.

Single Inheritance in Java

Single inheritance means one child class inherits from one parent class.

SingleInheritanceExample.java
Copy Try Download
class Vehicle {
    void start() {
        System.out.println("Vehicle starts");
    }
}

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

    public static void main(String[] args) {
        Car car = new Car();
        car.start();
        car.drive();
    }
}

Output:

Vehicle starts
Car drives

Explanation

  1. Vehicle is the parent class.
  2. Car inherits Vehicle using the extends keyword.
  3. The Car object can access both:
    • start()
    • drive()
  4. start() belongs to the Vehicle class.
  5. drive() belongs to the Car class.

Multilevel Inheritance in Java

Multilevel inheritance creates a chain of inheritance. For example, Dog inherits from Mammal, and Mammal inherits from Animal.

MultilevelInheritanceExample.java
Copy Try Download
class Animal {
    void eat() {
        System.out.println("Animal eats");
    }
}

class Mammal extends Animal {
    void walk() {
        System.out.println("Mammal walks");
    }
}

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

    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.eat();
        dog.walk();
        dog.bark();
    }
}

Output:

Animal eats
Mammal walks
Dog barks

Explanation

In multilevel inheritance, the child class object contains accessible members from all classes in the inheritance chain.

Dog object contains:
Animal members
+
Mammal members
+
Dog members
  1. Animal is the top-level parent class.
  2. Mammal extends Animal.
  3. Dog extends Mammal.
  4. The Dog object can access eat(), walk(), and bark().
  5. This is called multilevel inheritance because inheritance happens in a chain.

Hierarchical Inheritance in Java

Hierarchical inheritance means multiple child classes inherit from the same parent class.

HierarchicalInheritanceExample.java
Copy Try Download
class Shape {
    void draw() {
        System.out.println("Drawing shape");
    }
}

class Circle extends Shape {
    void circleInfo() {
        System.out.println("This is a circle");
    }
}

class Rectangle extends Shape {
    void rectangleInfo() {
        System.out.println("This is a rectangle");
    }

    public static void main(String[] args) {
        Circle c = new Circle();
        c.draw();
        c.circleInfo();

        Rectangle r = new Rectangle();
        r.draw();
        r.rectangleInfo();
    }
}

Output:

Drawing shape
This is a circle
Drawing shape
This is a rectangle

Explanation

In hierarchical inheritance, multiple child classes inherit from the same parent class. This means common functionality is written once in the parent class and reused by many child classes.

Inheritance Structure:
Shape
Circle
Rectangle
  1. Shape is the parent class.
  2. Circle inherits from Shape.
  3. Rectangle also inherits from Shape.
  4. The draw() method belongs to the Shape class.
  5. Both Circle and Rectangle objects can access draw().
  6. circleInfo() belongs only to the Circle class.
  7. rectangleInfo() belongs only to the Rectangle class.
``

Multiple Inheritance and Java

Java does not support multiple inheritance using classes. This means one class cannot extend two classes at the same time.

Language Multiple Inheritance using Classes
Java ❌ No
C++ ✅ Yes
Python ✅ Yes
Why Java is different? Java avoids multiple inheritance with classes to prevent ambiguity problems like the diamond problem. Instead, Java supports multiple inheritance-like behavior using interfaces.
MultipleInheritanceError.java
class A {
}

class B {
}

class C extends A, B { // Error
}

Output:

Compilation Error
Why? Java avoids multiple inheritance with classes to prevent ambiguity problems such as the diamond problem. Multiple inheritance-like behavior is achieved using interfaces.

Constructor Execution Order in Inheritance

When a child class object is created, the parent class constructor executes first, then the child class constructor executes.

ConstructorOrderExample.java
Copy Try Download
class Parent {
    Parent() {
        System.out.println("Parent constructor");
    }
}

class Child extends Parent {
    Child() {
        System.out.println("Child constructor");
    }

    public static void main(String[] args) {
        Child obj = new Child();
    }
}

Output:

Parent constructor
Child constructor
Create Child Object
new Child()
Memory Allocated
Space is created for parent and child class members.
Parent Constructor Executes
Java initializes the parent class part first.
Child Constructor Executes
Then Java initializes the child class part.
Object Ready
Now the child object can be used.

super Keyword Introduction

The super keyword refers to the parent class part of the current object. It is commonly used to call parent class constructor, parent class method, or parent class variable.

super can be used to

✓ call parent constructor

✓ call parent method

✓ access parent variable

SuperKeywordExample.java
Copy Try Download
class Parent {
    void show() {
        System.out.println("Parent show method");
    }
}

class Child extends Parent {
    void show() {
        super.show();
        System.out.println("Child show method");
    }

    public static void main(String[] args) {
        Child c = new Child();
        c.show();
    }
}

Output:

Parent show method
Child show method
Next Lesson: The super keyword will be explained deeply in the next Java OOP lesson.

Method Overriding Introduction

Method overriding happens when a child class provides its own implementation of a method that already exists in the parent class.

MethodOverridingExample.java
Copy Try Download
class Animal {
    void sound() {
        System.out.println("Animal makes sound");
    }
}

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

    public static void main(String[] args) {
        Dog d = new Dog();
        d.sound();
    }
}

Output:

Dog barks

Explanation

In method overriding, the child class provides its own version of a method that already exists in the parent class.

Execution Flow:
Animal defines sound()
Dog overrides sound()
Dog implementation executes
Runtime Polymorphism
  1. Animal class defines the sound() method.
  2. Dog class extends Animal.
  3. Dog class provides its own implementation of sound().
  4. When d.sound() is called, Java executes the Dog class version.
  5. This is an example of method overriding and runtime polymorphism.

protected Members in Inheritance

A protected member can be accessed in the same package and also in child classes. It is often used when parent class data or behavior should be available to subclasses.

ProtectedExample.java
Copy Try Download
class Employee {
    protected double salary = 50000;
}

class Developer extends Employee {
    void showSalary() {
        System.out.println("Salary: " + salary);
    }

    public static void main(String[] args) {
        Developer d = new Developer();
        d.showSalary();
    }
}

Output:

Salary: 50000.0

Upcasting in Inheritance

Upcasting means storing a child class object in a parent class reference variable. This is allowed because the child object is also a type of parent.

A Dog object is also an Animal because Dog extends Animal. Therefore, storing a Dog object in an Animal reference is called upcasting.

UpcastingExample.java
Copy Try Download
class Animal {
    void sound() {
        System.out.println("Animal sound");
    }
}

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

    public static void main(String[] args) {
        Animal a = new Dog();
        a.sound();
    }
}

Output:

Dog barks
Interview Point: In upcasting, overridden methods are resolved using the actual object at runtime.

Downcasting in Java

Downcasting means converting a parent class reference back into a child class reference. It requires explicit casting.

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

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

    public static void main(String[] args) {
        Animal a = new Dog(); // Upcasting

        Dog d = (Dog) a; // Downcasting
        d.bark();
    }
}

Output:

Dog barks
Important: Downcasting converts a parent reference back to a child reference. It requires explicit casting and is covered in detail in the Polymorphism lesson.

Inheritance Represents IS-A Relationship

Use inheritance only when the child class is truly a type of the parent class.

Relationship Correct? Reason
Dog is an Animal Yes Dog is a specific type of Animal.
Car is a Vehicle Yes Car is a specific type of Vehicle.
Car is an Engine No Car has an Engine. This is HAS-A, not IS-A.

Tricky Cases: If This, Then What Happens?

1. Are private members inherited?

PrivateMemberExample.java
class Parent {
    private int number = 10;
}

class Child extends Parent {
    void show() {
        System.out.println(number); // Error
    }
}

Output:

Compilation Error
Reason: Private members are not directly accessible in child classes. Use public or protected methods to access them safely.

2. Are constructors inherited?

Answer: No. Constructors are not inherited. However, a parent class constructor is called during child object creation.

3. What if parent class has only parameterized constructor?

ParameterizedParentError.java
class Parent {
    Parent(String name) {
        System.out.println(name);
    }
}

class Child extends Parent {
    Child() {
        System.out.println("Child constructor");
    }
}

Output:

Compilation Error
Reason: Java tries to call super() automatically, but the parent class does not have a no-argument constructor. The child constructor must call super("value") explicitly.

4. Can final class be inherited?

FinalClassExample.java
final class Parent {
}

class Child extends Parent { // Error
}

Output:

Compilation Error
Reason: A final class cannot be inherited.

5. Are static methods overridden?

Answer: No. Static methods are hidden, not overridden. Method overriding applies to instance methods.

Common Mistakes with Inheritance

  • Using inheritance when there is no IS-A relationship.
  • Trying to extend multiple classes in Java.
  • Thinking private members can be directly accessed in child classes.
  • Thinking constructors are inherited.
  • Forgetting to call super() when parent has only parameterized constructor.
  • Confusing method overriding with method overloading.
  • Thinking static methods are overridden.
  • Using inheritance where composition or HAS-A relationship is more appropriate.
  • Overusing inheritance instead of composition.
Summary:
  • Inheritance allows one class to acquire members of another class.
  • The extends keyword is used for class inheritance.
  • Inheritance supports code reusability and IS-A relationship.
  • Java supports single, multilevel, and hierarchical inheritance with classes.
  • Java does not support multiple inheritance with classes.
  • Constructors are not inherited, but parent constructors execute first.
  • Private members are not directly accessible in child classes.
  • Method overriding allows a child class to redefine parent class behavior.
  • super is used to access parent class members and constructors.

Interview Questions ⭐

Inheritance is a mechanism where one class acquires accessible members of another class. It helps in code reusability and represents an IS-A relationship.

The extends keyword is used for class inheritance in Java. A child class uses extends to inherit from a parent class.

The class whose members are inherited is called a parent class. It is also called a superclass or base class.

The class that inherits another class is called a child class. It is also called a subclass or derived class.

No, Java does not support multiple inheritance with classes. A Java class can extend only one class at a time.

Java does not support multiple inheritance with classes to avoid ambiguity problems such as the diamond problem. Multiple inheritance-like behavior can be achieved using interfaces.

No. Constructors are not inherited in Java, but parent class constructors are called during child object creation.

Private members are not directly accessible in child classes. They can be accessed indirectly through public or protected methods provided by the parent class.

Method overriding happens when a child class provides its own implementation of a method that already exists in the parent class.

The super keyword refers to the parent class part of the current object. It can be used to call a parent constructor, access a parent method, or access a parent variable.

IS-A relationship means the child class is a specific type of the parent class. For example, Dog IS-A Animal and Car IS-A Vehicle.

No. A final class cannot be inherited. If a class is declared final, no class can extend it.

IS-A relationship represents inheritance, where one class is a type of another class. HAS-A relationship represents composition, where one class contains or uses another class as a member. For example, Car IS-A Vehicle, but Car HAS-A Engine.

Inheritance represents an IS-A relationship and is used when one class is a specialized version of another class. Composition represents a HAS-A relationship and is used when one class contains another object as a part.

Single inheritance means one child class inherits from one parent class. Java supports single inheritance using the extends keyword.

Multilevel inheritance means inheritance occurs in a chain. For example, Animal is inherited by Mammal, and Mammal is inherited by Dog.

Hierarchical inheritance means multiple child classes inherit from the same parent class. For example, Circle and Rectangle can both inherit from Shape.

Hybrid inheritance is a combination of multiple inheritance types. Java does not support hybrid inheritance with classes directly, but it can be achieved using interfaces.

The syntax is: class ChildClass extends ParentClass. The child class inherits accessible members of the parent class.

Yes, a child class can access accessible parent class methods such as public and protected methods. Private methods are not directly accessible.

Yes, a child class can access accessible parent class variables such as public and protected variables. Private variables are not directly accessible.

When a child object is created, memory is allocated, then the parent constructor executes first, then the child constructor executes, and finally the object becomes ready.

The parent constructor executes first because the parent class part of the child object must be initialized before the child class part.

Yes. A child class constructor can call a parent class constructor using super(). If no explicit super() call is written, Java tries to insert super() automatically.

If the parent class has only a parameterized constructor, the child constructor must explicitly call it using super(arguments). Otherwise, a compilation error occurs.

Upcasting means storing a child class object in a parent class reference variable. For example, Animal a = new Dog();. It is allowed because a Dog is also an Animal.

Downcasting means converting a parent class reference back to a child class reference. It requires explicit casting, such as Dog d = (Dog) a;.

No. Downcasting is safe only if the parent reference actually refers to an object of the child class. Otherwise, ClassCastException can occur at runtime.

No. Static methods are not overridden. If a child class defines a static method with the same signature, it hides the parent class static method.

No. A final method cannot be overridden by a child class.

Final variables can be inherited if they are accessible, but their values cannot be changed after initialization.

Yes. Abstract classes are commonly used as parent classes. A child class can extend an abstract class and provide implementations for its abstract methods.

Object is the root class of Java class hierarchy. Every class in Java directly or indirectly inherits from Object.

A protected member can be accessed within the same package and by subclasses. It is commonly used when parent class members should be available to child classes.

Inheritance should be used when there is a true IS-A relationship between classes and when the child class is a specialized version of the parent class.

Composition should be preferred when the relationship is HAS-A rather than IS-A. For example, a Car HAS-A Engine, so composition is better than inheritance.

Next step: Learn Java super Keyword

🚀 Continue to Java super Keyword →

🧠 Test your understanding with a quick quiz



🚀 Quick Knowledge Check

Topic: Inheritance | Language: Java

Question 1 of 51
Q1. What is single inheritance?
Q2. Which statement is an example of downcasting?
Q3. In the code 'class Car extends Vehicle', which class is the child class?
Q4. What is upcasting?
Q5. Which relationship is better represented by composition?
Q6. When should inheritance be used?
Q7. What is multilevel inheritance?
Q8. Which access modifier is commonly used to allow subclass access?
Q9. What is IS-A relationship?
Q10. Which keyword is used to call a parent class constructor?
Q11. What is inheritance in Java?
Q12. What will be the output?
class Parent {
    Parent() {
        System.out.println("Parent constructor");
    }
}

class Child extends Parent {
    Child() {
        System.out.println("Child constructor");
    }

    public static void main(String[] args) {
        new Child();
    }
}
Q13. Are constructors inherited in Java?
Q14. What is hierarchical inheritance?
Q15. Which keyword is used to call another constructor in the same class?
Q16. What does the super keyword refer to?
Q17. Does Java support multiple inheritance with classes?
Q18. When should composition be preferred over inheritance?
Q19. Are private members directly accessible in child classes?
Q20. Which relationship is correct for inheritance?
Q21. Can a final method be overridden?
Q22. Which inheritance type is not supported with Java classes?
Q23. What will be the output?
class Animal {
    void eat() {
        System.out.println("Animal eats food");
    }
}

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

    public static void main(String[] args) {
        Dog d = new Dog();
        d.eat();
        d.bark();
    }
}
Q24. In hierarchical inheritance, what happens?
Q25. Which language supports multiple inheritance with classes?
Q26. Can a child class directly access a private variable of parent class?
Q27. What is the root class of Java class hierarchy?
Q28. What will be the output?
class Animal {
    void sound() {
        System.out.println("Animal sound");
    }
}

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

    public static void main(String[] args) {
        Dog d = new Dog();
        d.sound();
    }
}
Q29. Which keyword is used for class inheritance in Java?
Q30. What does a Dog object contain in multilevel inheritance Animal -> Mammal -> Dog?
Q31. Why does parent constructor execute before child constructor?
Q32. What is the difference between inheritance and composition?
Q33. What can super be used for?
Q34. What is resolved at runtime in upcasting when overridden method is called?
Q35. What will happen if a class extends a final class?
Q36. What is the difference between IS-A and HAS-A relationship?
Q37. Why does Java not support multiple inheritance with classes?
Q38. What happens if parent class has only parameterized constructor and child does not call super(arguments)?
Q39. What is a child class?
Q40. How does Java achieve multiple inheritance-like behavior?
Q41. What will be the output?
class Animal {
    void sound() {
        System.out.println("Animal sound");
    }
}

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

    public static void main(String[] args) {
        Animal a = new Dog();
        a.sound();
    }
}
Q42. Which statement is an example of upcasting?
Q43. Can static methods be overridden?
Q44. What is a parent class?
Q45. What will be the output?
class Parent {
    void show() {
        System.out.println("Parent show");
    }
}

class Child extends Parent {
    void show() {
        super.show();
        System.out.println("Child show");
    }

    public static void main(String[] args) {
        new Child().show();
    }
}
Q46. What is method overriding?
Q47. Can a final class be inherited?
Q48. In the code 'class Car extends Vehicle', which class is the parent class?
Q49. Which is a common inheritance mistake?
Q50. What happens if a class tries to extend two classes?
class A { }
class B { }
class C extends A, B { }
Q51. What is downcasting?

🎉 Great job! Continue learning Java OOP step by step.

Discussion

Ask questions, share suggestions, or discuss this lesson.

Please login or create an account to join the discussion and save your learning activity.

Loading comments...

Have you completed this lesson?

Mark this lesson as completed to track your learning progress. To keep track across devices, please login and save your learning progress.

Not completed yet.