Inheritance in Java.

Aemon Jabbar
Nov 6 · 3 min read

What is Inheritance?

Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. For example, a child inherits the qualities of his/her parents. With inheritance, we can reuse the fields and methods of the existing class. Hence, inheritance facilitates reusability and is an important concept of OOP.

Inheritance Syntax:

class subClass extends superclass {

//methods and fields

}

Types of Inheritance:

There are Various types of inheritance in Java.

1.Single Inheritance:In Single Inheritance one class extends another class (one class only).

2. Multiple Inheritance:In Multiple Inheritance, one class extending more than one class. Java does not support multiple inheritance.

3. Multilevel Inheritance:In Multilevel Inheritance,one class can inherit from derived class.Hence, the derived class becomes the base class of the new class.

4. Hierarchical Inheritance: In Hierarchical Inheritance, one class is inherited by many sub classes.

5. Hybrid Inheritance: Hybrid inheritance is a combination of Single and Multiple inheritance.

Java doesn’t support hybrid/Multiple inheritance

Example of Inheritance:

class Doctor {
void Doctor_Details() {
System.out.println("Doctor Details...");
}
}

class Surgeon extends Doctor {
void Surgeon_Details() {
System.out.println("Surgen Detail...");
}
}

public class Hospital {
public static void main(String args[]) {
Surgeon s = new Surgeon();
s.Doctor_Details();
s.Surgeon_Details();
}
}

Summary:

Except for the Object class, a class has exactly one direct superclass. A class inherits fields and methods from all its superclasses , whether direct or indirect. A subclass can override methods that it inherits, or it can hide fields or methods that it inherits.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade