Inheritance in Java

Inheritance is one of the key features of OOPS.  Inheritance in java allows one class to inherit the property of another class. The main objective of the inheritance is code reuse. When a class inherits the another class then it can access the all non-private members of that class.

Inheritance defines the IS-A relation between two classes. Inheritance can be understood in terms of parent-child relationship. A class inherits the another class using “extends” keyword.

Inheritance is the used for code reuse. The child class can access and use the all non-private members of the super class, you don’t need to declare all functions and members in the child class again and again.

In Java inheritance is declared using the extends keyword. You declare that one class extends another class by using the extends keyword in the class definition.

Types of Inheritance

Inheritance in Java

Single Inheritance:

When a class extends the another class, it’s called single inheritance in below example A2 is extending the A1 class. Also, A2 is accessing the A1’s method.(We can use dot(.) operator to access parent class members)

 

Hierarchical Inheritance:

In hierarchical inheritance, A class can be inherited by the many subclasses. In above-described figure class A1 is extended by class A2 and A3. It means both of the classes A2 and A3 can reuse the class A1’s code. Both of the classes can access the class A1’s non-private members.

 

Multilevel Inheritance :

Multi-level inheritance is possible in OOPs. Here one class extends another class and another class can extend that child class and so on. But it makes the execution slow.

In our example, A2 is the child class of A1 and A3 is the child class of A2. you can notice A3 is directly not inheriting the class A1 but A3 is able to access the members of the A1 just because A2 is the child class of A1 and A3 is the child class of A2. It’s called multi-level inheritance.

 

Multiple Inheritance :

Multiclass concepts refer one class extends more than one class. It means one child class can have more than one parent class. In Java, it’s not allowed. Let’s see with the help of the below-mentioned example, how multiple inheritances is not possible in Java.

In below-mentioned example, class A3 is extending the class A1 and A2 both, so class A3 can access the both class members simultaneously. In our case both of the class A1 and A2 have the common method message() , now we are calling message() so in such case JVM can’t decide which method can be called. In such case, you will get the compiler error.

 

Selenium Testing Video Tutorial:

If you liked this video, then please subscribe to our YouTube Channel for more video tutorials.

0 Comment

Leave a Reply