Inheritance in Java
In real life, we often reuse existing things instead of starting from scratch. For example, a new car model may reuse the engine design from an older model and only add improvements.
Java follows the same idea through inheritance. Inheritance allows one class to reuse the properties and behavior of another class.
What Is Inheritance?
Inheritance is an object-oriented feature where one class (child) acquires the fields and methods of another class (parent).
The existing class is called the parent (or superclass), and the new class is called the child (or subclass).
This helps reduce code duplication and improves maintainability.
Why Inheritance Is Important
In large applications, many classes share common behavior.
Instead of writing the same code again and again, inheritance allows us to write common logic once and reuse it across multiple classes.
This makes applications easier to expand and easier to maintain.
Inheritance Syntax in Java
Java uses the extends keyword to create inheritance.
Let’s start with a simple example.
class Animal {
void eat() {
System.out.println("This animal eats food");
}
}
Now we create a child class that inherits from Animal.
class Dog extends Animal {
void bark() {
System.out.println("The dog barks");
}
}
Using Inherited Methods
The child class automatically gets access to all public and protected methods of the parent class.
Let’s test this using the main method.
public class Demo {
public static void main(String[] args) {
Dog d = new Dog();
d.eat();
d.bark();
}
}
Even though eat() is not defined in the Dog class,
it can still be used because it is inherited from Animal.
Real-World Example
Consider a company management system.
- Employee → has name, ID, salary
- Manager → is an Employee + manages a team
- Developer → is an Employee + writes code
Instead of rewriting employee details for each role, inheritance allows all roles to reuse common employee information.
Types of Inheritance in Java
Java supports several types of inheritance using classes and interfaces.
- Single inheritance
- Multilevel inheritance
- Hierarchical inheritance
Java does not support multiple inheritance using classes to avoid complexity and ambiguity.
Important Rules of Inheritance
- A child class can access non-private members of the parent
- Private members are not directly accessible
- Constructors are not inherited
- Java supports only single inheritance with classes
What You Learned in This Lesson
- What inheritance is and why it is useful
- How to use the
extendskeyword - How child classes reuse parent class behavior
- Real-world use cases of inheritance
In the next lesson, you will learn about polymorphism, which allows objects to behave differently in different situations.