What is Inheritance?

1 answers

Inheritance provides an object with the ability to acquire the fields and methods of another class, called base class. Inheritance provides reusability of code and can be used to add additional features to an existing class, without modifying it.

Sample class Mammal is shown below which has a constructor.

public class Mammal{  
 
 public Mammal()
 {
   System.out.println("Mammal created"); 
 }
  
}

Man class extends Mammal which has a default constructor. The sample code is shown below.

 public class Man extends Mammal{ 
 public Man()
 {  
   System.out.println("Man is created");  
 }  
}

Inheritance is tested by creating an instance of Man using default constructor. The sample code is shown to demonstrate the inheritance.

public class TestInheritance{
 
public static void main(String args[])
{  
   Man man = new Man();  
 }  
}
shilpigupta22 shilpigupta22 [Author] 2 months ago votes 0