What is inheritance in OOP (Java)?

Inheritance is one of the core concepts of Object-Oriented Programming (OOP). It allows a class (called the child class or subclass) to inherit properties and behaviors (fields and methods) from another class (called the parent class or superclass). This promotes code reuse and establishes a natural relationship between classes.

What is inheritance in Java?

Inheritance is the mechanism in Java where one class acquires the properties (fields) and behaviors (methods) of another class. This allows the reuse of existing code and facilitates the addition of new features with minimal changes to the codebase.

Why do we need inheritance in Java?

  1. Code reusability: Reuse methods and variables from the parent class.

  2. Improved maintainability: Changes in the parent class reflect automatically in child classes.

  3. Real-world modeling: Models is-aAn "is-a relationship" in Java means one class inherits from another, like "a Car is-a Vehicle." relationships between objects.

  4. Polymorphism: Allows for method overriding to define specific behaviors in subclasses.

Consider a Vehicle as a superclass. It has properties like speed and fuelCapacity and methods like start() and stop(). A Car class can inherit from Vehicle and reuse these properties and methods while adding specific features like airConditioning or musicSystem.

Coding example for inheritance

// Parent Class
class Vehicle {
int speed; // Attribute to store the speed of the vehicle
int fuelCapacity; // Attribute to store the fuel capacity of the vehicle
// Method to start the vehicle
void start() {
System.out.println("Vehicle is starting...");
}
// Method to stop the vehicle
void stop() {
System.out.println("Vehicle is stopping...");
}
}
// Child Class
class Car extends Vehicle {
String airConditioning; // Attribute specific to Car, representing the air conditioning type
// Method to play music, specific to the Car class
void playMusic() {
System.out.println("Playing music in the car.");
}
}
public class InheritanceExample {
public static void main(String[] args) {
// Create an instance of the Car class
Car car = new Car();
// Assign values to inherited attributes
car.speed = 120;
car.fuelCapacity = 50;
// Assign value to the specific attribute of Car
car.airConditioning = "Automatic";
// Use inherited method to start the car
car.start();
// Display the car's speed
System.out.println("Car speed: " + car.speed);
// Use the Car-specific method to play music
car.playMusic();
// Use inherited method to stop the car
car.stop();
}
}

Explanation

The Vehicle class is the parent class, defining common attributes and methods such as speed, fuelCapacity, start(), and stop(). The Car class is a child class inheriting from Vehicle, adding its own unique attribute airConditioning and method playMusic(). The main method creates an instance of Car and uses both inherited and custom functionality.

Let’s explore the different ways inheritance can be implemented in Java.

Java inheritance types

Java supports several types of inheritance. Below are the types and their details:

1. Single inheritance

A single subclass inherits from one superclass. It models a simple "is-a" relationship where a subclass extends one parent class. For example, A Dog class inherits properties of an Animal class.

Example code

// Parent Class: Animal
class Animal {
// Method to simulate eating behavior
void eat() {
System.out.println("This animal eats food.");
}
}
// Child Class: Dog inherits from Animal
class Dog extends Animal {
// Method to simulate barking behavior
void bark() {
System.out.println("The dog barks.");
}
}
// Main Class
public class SingleInheritance {
public static void main(String[] args) {
// Create an object of Dog class
Dog dog = new Dog();
// Call inherited method from Animal class
dog.eat();
// Call method specific to Dog class
dog.bark();
}
}

Explanation

A child class (Dog) inherits from a single parent class (Animal). The Animal class defines a generic behavior (eat method), while the Dog class adds a specific behavior (bark method). The main method demonstrates how the Dog class can utilize both inherited and its own methods.

2. Multilevel inheritance

A class inherits from another class, which itself is inherited from a third class. It models a chain of inheritance, creating a hierarchical relationship. For example, A BabyDog class inherits from Dog, which in turn inherits from Animal.

A question arises that what happens if both parent and grandparent have the same function in multilevel inheritance. In multilevel inheritance, if both the parent and grandparent classes have a method with the same name and signature, the child class will inherit the method from the closest ancestor (the parent class).

Example Code

// Parent Class: Animal
class Animal {
// Method to simulate eating behavior
void eat() {
System.out.println("This animal eats food.");
}
}
// Intermediate Class: Dog inherits from Animal
class Dog extends Animal {
// Method to simulate barking behavior
void bark() {
System.out.println("The dog barks.");
}
}
// Child Class: BabyDog inherits from Dog
class BabyDog extends Dog {
// Method to simulate weeping behavior
void weep() {
System.out.println("The baby dog weeps.");
}
}
// Main Class
public class MultilevelInheritance {
public static void main(String[] args) {
// Create an object of BabyDog class
BabyDog babyDog = new BabyDog();
// Call inherited methods from Animal and Dog classes
babyDog.eat();
babyDog.bark();
// Call method specific to BabyDog class
babyDog.weep();
}
}

Explanation

A class (BabyDog) inherits from a child class (Dog), which in turn inherits from a parent class (Animal). Each class contributes specific behaviors, and the BabyDog class can access methods from all its ancestor classes.

Try this: Add a new method to the Dog class (e.g., play()) and call it from the BabyDog class.

3. Hierarchical inheritance

Multiple subclasses inherit from a single superclass. It promotes code reuse where multiple subclasses share common functionality from a parent class. For example, Cat and Dog classes both inherit from an Animal class.

Example Code

// Parent Class: Animal
class Animal {
// Method to simulate eating behavior
void eat() {
System.out.println("This animal eats food.");
}
}
// Subclass 1: Dog inherits from Animal
class Dog extends Animal {
// Method to simulate barking behavior
void bark() {
System.out.println("The dog barks.");
}
}
// Subclass 2: Cat inherits from Animal
class Cat extends Animal {
// Method to simulate meowing behavior
void meow() {
System.out.println("The cat meows.");
}
}
// Main Class
public class HierarchicalInheritance {
public static void main(String[] args) {
// Create an object of Dog class
Dog dog = new Dog();
dog.eat();
dog.bark();
// Create an object of Cat class
Cat cat = new Cat();
cat.eat();
cat.meow();
}
}

Explanation

Multiple subclasses (Dog and Cat) inherit from a single parent class (Animal). Each subclass adds its own specific behaviors while inheriting the common behavior from the parent class.

4. Multiple inheritance

Java doesn’t support multiple inheritance directly using classes to avoid ambiguity. Instead, it achieves multiple inheritance using interfaces. It allows a class to implement multiple interfaces, enabling flexible designs. For example, A Robot can implement both Worker and Machine interfaces.

Example code

// Interface 1: Worker
interface Worker {
// Abstract method for work behavior
void doWork();
}
// Interface 2: Machine
interface Machine {
// Abstract method for start behavior
void start();
}
// Implementing Class: Robot implements both interfaces
class Robot implements Worker, Machine {
// Implementation of Worker method
public void doWork() {
System.out.println("Robot is working.");
}
// Implementation of Machine method
public void start() {
System.out.println("Robot is starting.");
}
}
// Main Class
public class MultipleInheritance {
public static void main(String[] args) {
// Create an object of Robot class
Robot robot = new Robot();
// Call methods from both interfaces
robot.start();
robot.doWork();
}
}

Explanation

The Robot class implements two interfaces, Worker and Machine, providing specific implementations for their methods, doWork() and start(). The program shows how a single class can inherit behaviors from multiple sources, achieving flexibility and modularity.

5. Hybrid inheritance

Hybrid inheritance is a combination of two or more types of inheritance, like single and multiple inheritance. Java doesn’t support hybrid inheritance with classes to avoid complexity but achieves it through interfaces. For example, A class inherits from a superclass and also implements an interface.

Example code

// Parent Class: Vehicle
class Vehicle {
// Method to simulate running behavior
void run() {
System.out.println("Vehicle is running.");
}
}
// Interface: Electric
interface Electric {
// Abstract method for charging behavior
void charge();
}
// Child Class: ElectricCar extends Vehicle and implements Electric
class ElectricCar extends Vehicle implements Electric {
// Implementation of Electric method
public void charge() {
System.out.println("Electric car is charging.");
}
}
// Main Class
public class HybridInheritance {
public static void main(String[] args) {
// Create an object of ElectricCar class
ElectricCar car = new ElectricCar();
// Call inherited method from Vehicle class
car.run();
// Call implemented method from Electric interface
car.charge();
}
}

Explanation

The ElectricCar class extends the Vehicle class (inheriting its run() method) and implements the Electric interface (providing an implementation for the charge() method). This approach combines class inheritance with interface implementation to support multiple inheritance-like behavior.

Key takeaways

  1. Inheritance allows you to reuse existing code by extending a base class, reducing duplication and improving maintainability.

  2. Use inheritance to model "is-a" relationships, like Car is a Vehicle.

  3. Inheritance creates a clear class hierarchy, making code easier to understand and manage. Avoid overly deep inheritance trees to reduce complexity.

  4. Subclasses can override methods of the parent class, enabling dynamic method dispatch and more flexible code. This is essential for writing extensible and reusable code.

  5. Use appropriate access modifiers (protected, public, or private) to control visibility of members. Overuse of protected can lead to unintended access by subclasses.

  6. Overusing inheritance can lead to tightly coupled and harder-to-maintain code. Consider composition as an alternative when a class doesn't have a true "is-a" relationship.

  7. Java supports single inheritance to avoid the ambiguity of multiple inheritance (e.g., diamond problem). Use interfaces to simulate multiple inheritance if required.

  8. Inheritance can make debugging more challenging due to interactions between parent and child classes. Ensure proper testing of base and derived class functionalities.

1

What is the primary benefit of inheritance in Java?

A)

Reduces memory usage

B)

Enables method overloading

C)

Promotes code reuse and maintainability

Question 1 of 30 attempted

Unlock your Java potential and take control of your coding journey! Start learning Java today to explore more than inheritance, build Java-based applications, and become a Java developer now!

Frequently asked questions

Haven’t found what you were looking for? Contact Us


What are the 6 types of inheritance?

The six types of inheritance are:

  1. Single inheritance: One class inherits from another.
  2. Multiple inheritance: A class inherits from multiple classes.
  3. Multilevel inheritance: A class inherits from a derived class, creating a chain.
  4. Hierarchical inheritance: Multiple classes inherit from a single base class.
  5. Hybrid inheritance: A combination of multiple inheritance types.
  6. Multipath inheritance: Multiple inheritance paths can be formed, typically causing ambiguity.

Why do we need inheritance?

Inheritance promotes code reuse, reduces redundancy, and allows new classes to inherit properties and behaviors from existing ones. It helps in building a hierarchical class structure and enhances maintainability.


When should I use inheritance?

Inheritance should be used when there’s a clear “is-a” relationship between the base and derived classes. It’s ideal for extending existing functionality without modifying the base class, ensuring flexibility and scalability.


What is the main use of inheritance?

The main use of inheritance is to enable code reuse and establish relationships between classes, allowing one class to inherit properties and methods from another. This makes software development more efficient and modular.


Free Resources

Attributions:
  1. undefined by undefined