elibraryportal Logo

Inheritance in Java | Example

→ Inheritance is an important concepts of OOPs(Object Oriented Programming).

→ Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

→ Inheritance inherit the features(fields and methods) of one class to another class.

→ Inherit the properties of a class use of extends keyword .

→ Inheritance is a mechanism in which one object acquires all the properties and behaviors of a parent object.

Syntax:

Important Terminology:

  • Super Class or Parent Class:- It is also called a base class . The class whose features are inherited is known as super class(or a base class or a parent class).
  • Sub Class or Child Class:- The class that inherits the another class is known as sub class(or a derived class, extended class, or child class).

Example:

See in fig....

Inheritance in Java | Example

Full Example 1:

Inheritance in Java | Example

Types of inheritance in java

→ Threre are Three types of inheritance supported.

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

NOTE: Multiple inheritance and Hybrid Inheritance is not supported in java

1) Single Inheritance

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

Single Inheritance in Java | Example

Example :

Output

Inheritance in Java | Example

2) Multilevel Inheritance

→ There is a chain of inheritance, it is known as multilevel inheritance.

Multilevel Inheritance in Java | Example

Example :

Output

Mulilevel Inheritance in Java | Example

3) Hierarchical Inheritance

→ When two or more classes inherits a single class.

Hierarchical Inheritance in Java | Example

Example :

Output

Hierarchical Inheritance in Java | Example

Q.) Why multiple inheritance is not supported in java?

→ To reduce the complexity and simplify the language, see a scenario example where A, B, and C are three classes. The C class inherits A and B classes. If A and B classes have the same method and you call it from child class object, there will be ambiguity to call the method of A or B class.

Example :

Output

  Compile Time Error