The process by which one class acquires the properties(data members) and functionalities(methods) of another class is called inheritance. The aim of inheritance is to provide the reusability of code so that a class has to write only the unique features and rest of the common properties and functionalities can be extended from the another class.
Parent Class:
The class whose properties and functionalities are used(inherited) by another class is known as parent class, super class or Base class.
Child Class:
The class that extends the features of another class is known as child class, sub class or derived 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 { }
Inheritance Example
class Teacher
{ String designation = "Teacher"; String collegeName = "PICT"; 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:
PICT Teacher Physics Teaching
Types of inheritance
Single Inheritance: refers to a child and parent class relationship where a class extends the another class.
Multilevel inheritance: 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: 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.
Hybrid inheritance: Combination of more than one types of inheritance in a single program. For example class A & B extends class C and another class D extends class A then this is a hybrid inheritance example because it is a combination of single and hierarchical inheritance.
Multiple Inheritance: Java doesn’t support multiple inheritance
Example :
class ParentClass{ //Parent class constructor ParentClass(){ System.out.println("Constructor of Parent"); } void disp(){ System.out.println("Parent Method"); } } class JavaExample extends ParentClass{ JavaExample(){ System.out.println("Constructor of Child"); } void disp(){ System.out.println("Child Method"); //Calling the disp() method of parent class super.disp(); } public static void main(String args[]){ //Creating the object of child class JavaExample obj = new JavaExample(); obj.disp(); } }
The output is :
Constructor of Parent Constructor of Child Child Method Parent Method