Java utilizes inheritance as a mechanism where an object gains all the characteristics and actions of a parent object, constituting a crucial aspect of OOPs (Object-Oriented Programming).
In Java, inheritance allows the creation of new classes based on existing classes. By inheriting methods from a parent class, we can leverage the parent class's methods and fields. Additionally, it is possible to introduce new methods and fields within the inheriting class.
What is Inheritance?
In Java, the concept of inheritance allows a class to acquire properties and behaviors from another class known as a superclass or parent class. The class that inherits from a superclass is referred to as a subclass or child class. By implementing inheritance, a subclass gains the ability to utilize members of its superclass such as fields and methods, promoting code reuse and supporting a hierarchical structure.
In programming, inheritance signifies the relationship where one class is considered a specialized version of another class, often referred to as a parent-child relationship.
Why Use Inheritance in Java?
Inheritance serves crucial purposes in programming:
- Method Overriding: Inheritance enables a subclass to offer a distinct implementation of a method that is already defined in its superclass, facilitating runtime polymorphism.
- Code Reusability: By inheriting from a parent class, developers can recycle existing code, minimizing redundancy and enhancing code maintainability.
Terms used in Inheritance
Here are the important terms (terminologies) that are used in inheritance:
- Class: A class is a group of objects which have common properties. It is a template or blueprint from which objects are created.
- Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class, extended class, or child class.
- Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also called a base class or a parent class.
- Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and methods of the existing class when you create a new class. You can use the same fields and methods already defined in the previous class.
The extends Keyword
The keyword 'extends' is employed to generate a fresh class, known as a subclass, that is based on an already existing class, referred to as a superclass. This feature enables the subclass to acquire both the fields and methods present in the superclass.
Syntax
It has the following syntax:
class Subclass-name extends Superclass-name
{
//methods and fields
}
Java Inheritance Example
As illustrated in the diagram above, the class Programmer is a subclass of the class Employee. The connection between these two classes is that Programmer is a specific kind of Employee, following the IS-A relationship. This signifies that a Programmer is categorized as an Employee.
This illustration showcases the concept of single inheritance in Java. In this scenario, the Programmer class inherits the salary attribute from the Employee class while also introducing its own bonus attribute.
Example
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
}
public class Main{
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Output:
Programmer salary is:40000.0
Bonus of programmer is:10000
In the given scenario, the Programmer object is capable of accessing the fields within its own class and also those of the Employee class, demonstrating code reusability.
Types of Inheritance
There are several types of inheritance supported in Java:
- Single Inheritance: Single inheritance allows a subclass inherits from one superclass only.
- Multilevel Inheritance: Multilevel inheritance allows a class is derived from a subclass, forming a chain of inheritance.
- Hierarchical Inheritance: Hierarchical inheritance allows multiple subclasses inherit from the same superclass.
- Hybrid Inheritance (Through Interfaces): Hybrid inheritance combines two or more types of inheritance using interfaces to avoid multiple inheritance issues.
Java enables multiple inheritance and hybrid inheritance using interfaces since direct multiple inheritance with classes is not permitted in Java. Further details on interfaces will be covered in later sections.
Single Inheritance
In the realm of object-oriented programming, when a class acquires properties and behaviors from another class, this is referred to as single inheritance. For instance, in the scenario illustrated below, the Dog class inherits characteristics from the Animal class, demonstrating single inheritance in action.
Let's illustrate the concept of single inheritance in Java with an example.
Example
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
public class Main{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
Output:
barking...
eating...
Multilevel Inheritance
In programming, a sequence of inheritance is referred to as multilevel inheritance. For instance, in the provided example, the BabyDog class inherits from the Dog class, which in turn inherits from the Animal class, demonstrating multilevel inheritance.
In this instance, we will use a sample to illustrate the functionality of multilevel inheritance in the Java programming language.
Example
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
public class Main{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Output:
weeping...
barking...
eating...
Hierarchical Inheritance
Hierarchical inheritance occurs when two or more classes inherit from a single class. In the provided example, the Dog and Cat classes both inherit from the Animal class, demonstrating hierarchical inheritance.
In this instance, we will illustrate how hierarchical inheritance functions in Java using an example.
Example
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
public class Main{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Output:
meowing...
eating...
Multiple Inheritance
Multiple Inheritance is the ability of a class to inherit characteristics from multiple classes. This concept can be valuable when a class requires functionalities from multiple origins.
Multiple inheritance can introduce challenges such as the diamond problem, a situation where two parent classes have a method or attribute in common, leading to conflicts. Java addresses this by employing interfaces to support multiple inheritance and avoid such conflicts.
In this instance, we will showcase the functionality of multiple inheritance in Java through an example.
Example
interface Character {
void attack();
}
interface Weapon {
void use();
}
class Warrior implements Character, Weapon {
public void attack() {
System.out.println("Warrior attacks with a sword.");
}
public void use() {
System.out.println("Warrior uses a sword.");
}
}
class Mage implements Character, Weapon {
public void attack() {
System.out.println("Mage attacks with a wand.");
}
public void use() {
System.out.println("Mage uses a wand.");
}
}
public class Main {
public static void main(String[] args) {
Warrior warrior = new Warrior();
Mage mage = new Mage();
warrior.attack(); // Output: Warrior attacks with a sword.
warrior.use(); // Output: Warrior uses a sword.
mage.attack(); // Output: Mage attacks with a wand.
mage.use(); // Output: Mage uses a wand.
}
}
Output:
Warrior attacks with a sword.
Warrior uses a sword.
Mage attacks with a wand.
Mage uses a wand.
Hybrid Inheritance in Java
Hybrid inheritance involves combining two or more forms of inheritance. Its primary objective is to organize the code into distinct classes effectively, promoting code reusability.
The hybrid inheritance can be achieved by using the following combinations:
- Single and Multiple Inheritance (not supported but can be achieved through interface)
- Multilevel and Hierarchical Inheritance
- Hierarchical and Single Inheritance
- Multiple and Multilevel Inheritance
In this instance, we will use an example to illustrate how hybrid inheritance operates in the Java programming language.
Example
class C
{
public void disp()
{
System.out.println("C");
}
}
class A extends C
{
public void disp()
{
System.out.println("A");
}
}
class B extends C
{
public void disp()
{
System.out.println("B");
}
}
public class D extends A
{
public void disp()
{
System.out.println("D");
}
public static void main(String args[])
{
D obj = new D();
obj.disp();
}
}
Output:
FAQs about Inheritance
1. Why multiple inheritance is not supported in Java?
In Java, the absence of support for multiple inheritance is a deliberate choice aimed at reducing complexity and making the language more straightforward.
Consider a scenario where there are three classes named ClassA, ClassB, and ClassC. ClassC inherits from both ClassA and ClassB. If both ClassA and ClassB contain a method with the same name, when we try to invoke this method using an object of ClassC, there arises ambiguity in determining whether to call the method from ClassA or ClassB. This situation is commonly referred to as the "diamond problem" in object-oriented programming.
To read more Diamond Problem in Java
Java identifies the issue of inheriting two classes by generating a compile-time error, which is considered preferable to encountering runtime errors. In this scenario, regardless of whether the inherited classes contain identical or distinct methods, a compile-time error will occur.
class A {
void msg(){System.out.println("Hello");}
}
class B {
void msg(){System.out.println("Welcome");}
}
public class Main extends A,B {
public static void main(String args[]){
Main obj = new Main();
obj.msg();//Now which msg() method would be invoked?
}
}
Output:
Compile Time Error
2. How to achieve Multiple Inheritance in Java?
In Java, the feature of multiple inheritance is achieved exclusively through interfaces, allowing a class to implement more than one interface. While Java does not support multiple inheritance through classes, it does allow it through interfaces.