Java

What is Inheritance ?

What is Inheritance ?

Inheritance is a process where a class can aquire properties of another class ie methods and fields.

A class who inherits or extend the properties of other class is known as subclass, derived class or child class and the class whose properties are inherited or extended is called as superclass, base class or parent class.

In general life a child or son can be use the property (House, car, office and cloths etc)

A child class inherit parent class with the help of extends keyword, and a child class can inherit only one super or parent class .

 

extends

extends is a keyword which is used to inherit the super, parent class from child class.

 

Advantage of Inheritance

  1. Method overloading
  2. Code Reusability

 

Syntax

class ParentClass {

. . . . .

. . . . .

. . . . .

}

class ChildClass extends ParentClass {

. . . . .

. . . . .

. . . . .

}

 

Example

class ParentClass

{

public void showParent()

{

System.out.println(“this is parent class method”);

}

}

public class ChildClass extends ParentClass

{

public void showChild()

{

System.out.println(“this is child class method “);

}

public static void main(String[] args)

{

ChildClass objChild = new ChildClass ();

objChild.showChild (); // this is child class method

objChild.showParent(); // this is parent class method

}

}

 

Output

this is child class method

this is parent class method

Types of Inheritance

  1. Single Inheritance
  2. Multilevel Inheritance
  3. Heirarchical Inheritance

NOTE : Multiple inheritance is not supported in java

 

Super Keyword

Super keyword is used to refer parent class fo a child class.

class ParentClass

{

String nameVariable;

String nameVar;

public void show()

{

nameVar = “Parent another variable”;

System.out.println(nameVar);

}

}

public class ChildClass extends ParentClass

{

String nameVariable;

public void show()

{

super. show(); //calling Parent class show() method

super.nameVariable = “Parent Class Variable”; //parent class member

name = “Child Class Variable”;

System.out.println(super.nameVariable +” and “+nameVariable);

}

public static void main(String[] args)

{

ChildClass objChild = new ChildClass();

objChild. show();

}

}

 

Output

Parent another variable

Parent Class Variable and Child Class Variable

Leave a Reply

Your email address will not be published. Required fields are marked *