What is Inheritance in Java and How to Implement It?

What is Inheritance in Java and How to Implement It?

Inheritance in Java is a fundamental mechanism where one object inherits all the attributes and behaviors of a parent object. It is an essential part of OOPs.

In Java, Inheritance allows you to create new classes by building upon pre-existing classes. When you inherit from an existing class, it’s like borrowing its methods and properties. Plus, you can also throw in some new methods and properties of your own in your new class.

Why Use Inheritance in Java

  • Code Reusability: Inheritance helps you recycle code. If you have a class that does something useful, you can make a new class that uses everything from the first one, saving you from writing the same code all over again.
  • Extensibility: You can add new things to your class. Imagine you have a “Vehicle” class. With Inheritance, you can create a “Car” class that’s a type of vehicle with its unique car-related stuff.
  • Organized Hierarchy: Inheritance helps you organize your classes. Think of it like creating a family tree for your classes. You can group related things. For example, all animals have some common traits, so you can put them in the “Animal” group and then make subclasses like “Dog” and “Cat.”
  • Polymorphism: Inheritance is like having a common language. Even if you have different types of objects, they can all understand the same language (methods). So you can use them flexibly and dynamically in your program.

Terms Used in Inheritance

  • Class: A class is a fundamental concept in object-oriented programming (OOP). It serves as a blueprint or template for creating objects. In a class, you define the properties (attributes) and behaviors (methods) that objects created from that class will have.
  • Child-class/sub-class: A subclass, in object-oriented programming, is a class that inherits attributes and behaviors from another class, often referred to as the superclass or parent class. The subclass extends or specializes the functionality of the parent class by adding new attributes and methods or modifying the inherited ones.
  • Parent Class/Super Class: A parent class, also known as a superclass or base class, is a class from which one or more other classes, called child classes or subclasses, inherit properties and behaviors. In object-oriented programming (OOP), the parent class serves as a blueprint or template for the child classes, defining common attributes and methods that the child classes can use.

Syntax of Java Inheritance:


 class childclass-name extends Parentclass-name  
	{  
		//methods and attributes  
	}

Java Inheritance Example

Java Inheritance

As displayed in the above figure, MountainBike is the subclass, and Bicycle is the superclass. The relationship between the two classes is MountainBike IS-A Bicycle. It means that MountainBike is a type of Bicycle.

Example

class Bicycle {  
    public int gear = 5;
} 
class MountainBike extends Bicycle {  
    public int seatHeight = 100;
    
    public static void main(String args[]) {  
        MountainBike m = new MountainBike();  
        System.out.println("Bicycle gear is: " + m.gear);  
        System.out.println("Seat height of Bicycle is: " + m.seatHeight);  
    }  
}
Output:
Bicycle gear is:5
 	seatHeight of Bicycle is:100

In the provided example, a MountainBike object can access its own class’s fields and the fields of the Bicycle class; this is a principle of code reusability in object-oriented programming.

Types of Inheritance in Java

Inheritance can be categorized into three main types:

  1. Single Inheritance,
  2. Multilevel Inheritance,
  3. Hierarchical inheritance.

In Java programming, multiple and hybrid Inheritance is supported through the interface only.

1) Single Inheritance

When a class inherits another class, it is known as a single inheritance.

Single Inheritance

In your example, the “Apple” class is like a student who learns from a “Fruit” teacher. This is an example of single Inheritance, where a student (Apple) learns from one teacher (Fruit).

Example

class Fruit {
	    void fruit() {
	        System.out.println("This is a fruit.");
	    }
	}
	class Apple extends Fruit {
	    void display() {
	        System.out.println("This is an apple.");
	    }
	}
	public class Main {
	    public static void main(String[] args) {
	        Apple apple = new Apple();
	        apple.display(); // Calls the display method of Apple
	        apple.fruit();  // Calls the fruit method of Fruit
	    }
	}

Output

This is an apple.
This is a fruit.

2) Multilevel Inheritance

Multilevel Inheritance in programming occurs when a class inherits from another class, and then another class inherits from that derived class, creating a chain of Inheritance. This means that the derived class becomes a parent class for another class.

Multilevel Inheritance

In the example, the green Apple class inherits from the Apple class, which again inherits from the Fruit class, creating a multilevel inheritance structure.

Example


class Fruit {  
    void fruit() {
        System.out.println("This is a fruit.");
    }
}  

class Apple extends Fruit {  
    void apple() {
        System.out.println("This is an apple.");
    }  
}  

class GreenApple extends Apple {  
    void greenApple() {
        System.out.println("This is a Green apple.");
    }  
}  

class Main {  
    public static void main(String args[]) {  
        GreenApple g = new GreenApple();  
        g.fruit();
        g.apple();
        g.greenApple();
    }
}

Output

This is a fruit.
This is an apple.
This is a Green apple.

3) Hierarchical Inheritance

In this inheritance structure, multiple child classes inherit properties and behaviors from the same parent class. Each child class can have its unique attributes and methods, but they all share a standard base class.

Hierarchical Inheritance

In the provided example, the Apple class inherits from the Fruit class, and the Mango class inherits from the Fruit class, creating a Hierarchical inheritance structure.

Example

class Fruit{  
		void fruit() {
	        System.out.println("This is a fruit.");
	    }
	}  
	class Apple extends Fruit{  
		void apple(){
		 	System.out.println("This is an apple.");
		}  
	}  
	class Mango extends Fruit
{  
		void mango()
{
			System.out.println("This is a Mango.");
}  
}  
	class Main{  
		public static void main(String args[]){  
			Apple a=new Apple();  
			a.fruit();
			a.apple();
			Mango m=new Mango();  
			m.fruit();
			m.mango();
		}
	}

Output
This is a fruit.
This is an apple.
This is a fruit.
This is a Mango.

Why is multiple Inheritance not supported in Java?

Java does not support multiple Inheritance to maintain language simplicity and reduce complexity.

In a scenario where you have three classes, D, E, and F, with class F inheriting from both D and E, ambiguity can arise when D and E have a method with the same name. When you attempt to call this method using a child class object, it becomes unclear whether you intend to call the method from class D or class E.

Java’s design philosophy prioritizes compile-time errors over runtime errors for predictability and robustness. Therefore, in cases of multiple Inheritance, whether the methods in the parent classes are the same or different, Java enforces a compile-time error to address the ambiguity and ensure clarity in code execution.

Example

class D{  
		void message(){System.out.println("Hello");}  
	}  
	class E{  
		void message(){System.out.println("Welcome");}  
	}  
	class F extends D,E{//suppose if it were  
	   
		 public static void main(String args[]){  
		   F obj=new F();  
		   obj.message();//Now which message() method would be invoked?  
		}  
	}

Output
Compile Time Error