Inheritance

unza farhat
Nov 6 · 3 min read

Inheritance in java is a mechanism in which child object inherit all the properties and behaviours of parent object.

The idea behind inheritance in java is that you can create new classes that are build upon existing classes.When we inherit from an existing class,we can reuse methods and fields of the parent class.

Child Class:The class that extends the methods and fields of another class,This is known as child class,sub class or derived class.

Parent Class:The class whose properties and functionality are used by another class is known as parent class,super class or base class.

Why we use inheritance in java

In java,inheritance is used when a class wants to inherit the features of another existing class.Inheritance is used to use the existing features of a class.

Syntax: Inheritance in Java

To inherit a class we use extends keyword. Here class XYZ is child class and class ABC is parent class. The class XYZ is inheriting the properties and methods of ABC class.

class XYZ extends ABC
{
}

Types of Inheritance

Single Inheritance:It refers to a child and parent class relationship where a class extends the another class.

Multilevel Inheritance:It refers to a child and parent class relationship where a class extends the child class. For example class C extends class B and class B extends class A.

Hierarchical inheritance:It refers to a child and parent class relationship where more than one classes extends the same class. For example, classes B, C & D extends the same class A.

Multiple Inheritance:It refers to the concept of one class extending more than one classes, which means a child class has two parent classes. For example class C extends both classes A and B. Java doesn’t support multiple inheritance.

Hybrid inheritance: Combination of more than one types of inheritance in a single program.

Example of Inheritance

class XYZ extends ABC
{
}
class Teacher {
String designation = "Teacher";
String collegeName = "Beginnersbook";
void does(){
System.out.println("Teaching");
}
}

public class PhysicsTeacher extends Teacher{
String mainSubject = "Physics";
public static void main(String args[]){
PhysicsTeacher obj = new PhysicsTeacher();
System.out.println(obj.collegeName);
System.out.println(obj.designation);
System.out.println(obj.mainSubject);
obj.does();
}
}

Output:

Beginnersbook
Teacher
Physics
Teaching

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