Inheritance is an important concept in Java's object-oriented programming (OOP). It allows one class to acquire the properties and behaviors of another class, making it easier to reuse existing code.
In this article, we will understand what inheritance is, how it works in Java, its different types, and how keywords such as extends and super are used with inheritance.
Table of Contents
1. What Is Inheritance in Java?
Inheritance in Java is a mechanism through which one class can acquire the properties and methods of another class. It allows a new class to reuse and extend the functionality of an existing class.
The class whose properties and methods are inherited is called the parent class or superclass, while the class that inherits them is called the child class or subclass.
For example:
class Animal {
void eat() {
System.out.println("Animal eats");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}
Here, Animal is the parent class and Dog is the child class. Since Dog extends Animal, a Dog object can use the eat() method along with its own bark() method.
Dog d = new Dog(); d.eat(); d.bark();
Inheritance establishes an "is-a" relationship between classes. For example, a dog is an animal, so Dog can inherit from Animal.
In short, inheritance allows a class to reuse and extend the functionality of another class, reducing code duplication and supporting code reusability.
2. Why Is Inheritance Used in Java?
Inheritance allows developers to build new classes from existing ones instead of writing the same code repeatedly. It is mainly used to improve code reusability, organization, and maintainability.
Some key reasons for using inheritance are:
- Code reusability: A child class can reuse the fields and methods of its parent class.
- Reduced code duplication: Common functionality can be defined once in the parent class instead of being repeated in multiple classes.
- Method overriding: A child class can provide its own implementation of a method inherited from the parent class.
- Better organization: Related classes can be arranged in a clear hierarchy.
- Support for polymorphism: Inheritance allows objects of child classes to be treated as objects of their parent class, which supports runtime polymorphism.
For example, if several types of vehicles share common properties such as speed and methods such as start(), these can be placed in a Vehicle class. Classes such as Car and Bike can then inherit that functionality.
In short, inheritance helps Java programs reuse existing code while creating specialized classes with additional or modified behavior.
3. How Inheritance Works in Java
Inheritance works by creating a relationship between a parent class and a child class. The child class can use accessible fields and methods of the parent class and can also add its own members.
Java uses the extends keyword to create inheritance between classes.
Example:
class Vehicle {
void start() {
System.out.println("Vehicle starts");
}
}
class Car extends Vehicle {
void drive() {
System.out.println("Car is driving");
}
}
Here, Car extends Vehicle, so a Car object can access the start() method inherited from Vehicle as well as its own drive() method.
Car car = new Car(); car.start(); car.drive();
Output:
Vehicle starts Car is driving
The inheritance relationship can be represented as:
Vehicle → Car
The parent class provides common functionality, while the child class can add more specific functionality or override inherited methods.
Important Point:
Inheritance does not mean that every member of the parent class is directly accessible in the child class. For example, private members of the parent class cannot be accessed directly by the child class.
In short, inheritance allows a child class to build upon an existing parent class, creating reusable and organized class hierarchies.
4. Types of Inheritance in Java
Java supports different forms of inheritance based on how classes are related to each other. The main types are single, multilevel, hierarchical, and hybrid inheritance.| Type | Description |
|---|---|
| Single Inheritance | A single child class inherits from one parent class. |
| Multi Level Inheritance | A class inherits from another class, which itself inherits from a third class, forming a chain of inheritance. |
| Hierarchical Inheritance | Multiple child classes inherit from the same parent class. |
| Hybrid Inheritance | Hybrid Inheritance combines multiple forms of inheritance in a single class hierarchy. Java does not support hybrid inheritance through classes when it creates multiple inheritance. |
1. Single Inheritance:
One child class inherits from one parent class.
class Animal {
void eat() {
System.out.println("Eating");
}
}
class Dog extends Animal {
}
Here, Dog inherits from Animal.
2. Multilevel Inheritance:
Inheritance occurs across multiple levels.
class Animal {
}
class Dog extends Animal {
}
class Puppy extends Dog {
}
Here, Puppy inherits from Dog, while Dog inherits from Animal.
3. Hierarchical Inheritance:
Multiple child classes inherit from the same parent class.
class Animal {
}
class Dog extends Animal {
}
class Cat extends Animal {
}
Here, both Dog and Cat inherit from Animal.
4. Hybrid Inheritance:
Hybrid inheritance combines different inheritance structures. Java does not support hybrid inheritance using classes when it involves multiple inheritance because it can create ambiguity.
However, similar structures can be achieved using interfaces, which allow a Java class to implement multiple interfaces.
What About Multiple Inheritance?
Java does not allow a class to directly inherit from multiple classes.
For example, this is not valid:
class C extends A, B {
}
Java avoids this to prevent ambiguity about which parent's methods or fields should be inherited.
In short, Java supports single, multilevel, and hierarchical inheritance through classes, while multiple inheritance of classes is not supported. Interfaces can be used when multiple inheritance-like behavior is required.
5. Inheritance Using the extends Keyword
Java uses the extends keyword to create an inheritance relationship between two classes. It indicates that the child class should inherit accessible members from the parent class.
Syntax:
class ChildClass extends ParentClass {
// child class members
}
Example:
class Animal {
void eat() {
System.out.println("Animal eats");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}
class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat();
dog.bark();
}
}
Output:
Animal eats Dog barks
Here, Dog extends Animal, so the Dog class can use the inherited eat() method along with its own bark() method.
The extends keyword can be used when a class inherits from one other class. Java does not allow a class to extend multiple classes.
In short, the extends keyword establishes inheritance between a child class and a parent class, allowing the child class to reuse and extend the parent's functionality.
6. Method Overriding in Inheritance
Method overriding occurs when a child class provides its own implementation of a method that is already defined in its parent class. It allows the child class to change inherited behavior according to its specific requirements.
Example:
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
}
Here, the Dog class overrides the sound() method inherited from Animal.
Dog dog = new Dog(); dog.sound();
Output:
Dog barks
The @Override annotation tells the compiler that the method is intended to override a method from the parent class. It is recommended because it helps detect mistakes in the method declaration.
Rules for Method Overriding
- The child method must have the same method signature as the parent method.
- The overriding method cannot have a more restrictive access modifier than the parent method.
- final methods cannot be overridden.
- static methods are not overridden; they are hidden when a child class declares a static method with the same signature.
- Constructors cannot be overridden because they are not inherited.
Method overriding is an important part of runtime polymorphism, because Java can determine which overridden method to execute based on the actual object at runtime.
In short, method overriding allows a child class to provide a more specific implementation of an inherited method.
7.super Keyword in Inheritance
The super keyword in Java is used to refer to the immediate parent class. It is commonly used when a child class needs to access a parent class's variables, methods, or constructor.
1. Accessing Parent Class Variables
When a child and parent class have variables with the same name, super can be used to access the parent's variable.
class Animal {
String name = "Animal";
}
class Dog extends Animal {
String name = "Dog";
void display() { System.out.println(super.name);
System.out.println(name);
}
}
Here, super.name refers to the name variable of the parent class, while name refers to the child class's variable.
2. Calling a Parent Class Method
The super keyword can also be used to call a method from the parent class.
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
super.sound();
System.out.println("Dog barks");
}
}
Here, super.sound() calls the original method from the Animal class before the child class adds its own behavior.
3. Calling a Parent Class Constructor
super() can be used to call the constructor of the parent class.
class Animal {
Animal() {
System.out.println("Animal constructor");
}
}
class Dog extends Animal {
Dog() {
super();
System.out.println("Dog constructor");
}
}
The call to super() must be the first statement inside the child class constructor.
In short, super allows a child class to access or invoke members of its immediate parent class.
8. Advantages and Disadvantages of Inheritance
Inheritance can make Java programs easier to reuse and organize, but it can also introduce unnecessary complexity when used incorrectly.
Advantages of Inheritance:- Code reusability: A child class can reuse accessible fields and methods from its parent class.
- Reduced code duplication: Common functionality can be written once in the parent class instead of being repeated in multiple classes.
- Easy maintenance: Changes to shared functionality can be made in the parent class and reused by its child classes.
- Supports polymorphism: Inheritance allows parent class references to work with child class objects, supporting runtime polymorphism.
- Better organization: Related classes can be arranged into a clear hierarchy.
Disadvantages of Inheritance:
- Tight coupling: A child class becomes dependent on the implementation of its parent class.
- Reduced flexibility: Changing a parent class can sometimes affect multiple child classes.
- Complex hierarchies: Deep or poorly designed inheritance structures can make code difficult to understand.
- Not always suitable for reuse: Sometimes composition is a better choice than inheritance when classes do not have a natural “is-a” relationship.
In short, inheritance is useful for sharing common functionality and creating class hierarchies, but it should be used when there is a clear and meaningful relationship between the classes.
9. Common Mistakes and Best Practices
Inheritance is powerful, but using it without a clear class relationship can make code harder to maintain. The following practices can help you use inheritance effectively.
- Using inheritance only for code reuse: A child class should have a genuine “is-a” relationship with its parent class.
- Creating deep inheritance hierarchies: Too many levels of inheritance can make code difficult to understand and modify.
- Overriding methods incorrectly: The child method should follow the correct method signature and overriding rules.
- Ignoring access modifiers: Private members of a parent class cannot be accessed directly by its child class.
- Using inheritance when composition is better: If one class simply needs to use another class rather than represent a specialized version of it, composition may be more appropriate.
Best Practices:
- Keep inheritance hierarchies simple and meaningful.
- Use the @Override annotation when overriding methods.
- Use the super keyword when you need to explicitly access a parent class's members.
- Prefer composition when there is a “has-a” relationship instead of an “is-a” relationship.
- Design parent classes with common and reusable functionality that genuinely applies to their child classes.
In short, inheritance works best when the relationship between the parent and child classes is clear, logical, and easy to maintain.
10. Conclusion
Inheritance allows a Java class to reuse and extend the properties and methods of another class. By using concepts such as extends, method overriding, and super, developers can create organized and reusable class hierarchies.
11. Frequently Asked Questions
1. What is inheritance in Java?
Inheritance is a feature that allows one class to acquire accessible properties and methods from another class.
2. Which keyword is used for inheritance in Java?
The extends keyword is used when one class inherits from another class.
3. Does Java support multiple inheritance?
Java does not support multiple inheritance through classes. However, multiple interfaces can be implemented by a single class.
4. What is method overriding in Java?
Method overriding occurs when a child class provides its own implementation of a method inherited from its parent class.
5. What is the use of super in inheritance?
The super keyword is used to access members of the immediate parent class, including its variables, methods, and constructor.
0 Comments