JAVA | What is inheritance? List types of inheritance and explain single level inheritance with example.

Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. The idea behind inheritance is that we can create new classes that are built upon existing classes. When we inherit from an existing class, we can reuse methods and fields of the parent class. 

syntax 

class Subclass-name extends Superclass-name  
{  
   //methods and fields  
}   
A class which is inherited is called a parent or superclass, and the new class is
called child or subclass. 

Types of inheritance
1)Single inheritance 
2)Multilevel inheritance
3)Multiple inheritance
4)Hierarchical inheritance

Single level Inheritance 

In single inheritance, subclasses inherit the features of one superclass. In image below, the class A serves as a base class for the derived class B. 

For example 
class one  
{   
int v1=10; 
          void method1()  
          {  
             System.out.println("we are in method 1");  
            }  
}  
 class two extends one 
{  
void method2()  
{                  
 System.out.println("v1="+v1); 
            System.out.println("we are in method 2"); 
 }  
}  
 class singleinherit 
{  
 public static void main(String[] args)  
 {  
  two t = new two();  
                    t.method1(); 
                    t.method2(); 
            }  

Output: 
we are in method 1 
v1=10; 
we are in method 2

Post a Comment

0 Comments