You are on page 1of 2

Inheritance :

Creating new classes that bulid upon the Existing classes.


The Properties of One class is inherited to the Another Class
Parent-Child relationship
-------------------------------------------------------------------------------
Uses of Inheritance :
Code Reusability
Run time Polymorphism

Super/Parent/Base Class
Sub/Child/Derived Class

Reusability : Can reuse the methods and the fields of existing class in the new
classes
-------------------------------------------------------------------------------
class Super{
//Parent/Base
}
class Sub extends Super{
//Child/Derived
}

extends Keyword :
To increase the functionality the new class can be derived from the Existing
class using the keyword extends.
-------------------------------------------------------------------------------
Types of Inheritance :
>> Single
>> Multilevel
>> Hierarchical

>> Multiple Inheritance /Hybrid Inheritance can be Supported only by means of


interfaces
-------------------------------------------------------------------------------
Why Multiple Inheritance are not supported in java?
To decrease the Complexity and Simplify the Language the Multiple Inheritance
are not supported in java.
Consider , if Base Class 1 and Base class 2 has methods with same name .
If we try to call the base class method using the derived class Object,the compiler
doesnot know which method to call.Hence,Naming collison occurs
-------------------------------------------------------------------------------
Constructor Calling :
>> Using "super" Keyword
>> Constructor cannot be inherited
>> Whenever the parent child class has methods of same name to resolve the
ambiguity we use the "super" keyword in Java.
-------------------------------------------------------------------------------
Sample Code :
Single Inheritance :

Class A
{
public void methodA()
{
System.out.println("Base class method");
}
}

Class B extends A
{
public void methodB()
{
System.out.println("Child class method");
}
public static void main(String args[])
{
B obj = new B();
obj.methodA(); //calling super class method
obj.methodB(); //calling local method
}
}

Multilevel Inheritance example program in Java

Class X
{
public void methodX()
{
System.out.println("Class X method");
}
}
Class Y extends X
{
public void methodY()
{
System.out.println("class Y method");
}
}
Class Z extends Y
{
public void methodZ()
{
System.out.println("class Z method");
}
public static void main(String args[])
{
Z obj = new Z();
obj.methodX(); //calling grand parent class method
obj.methodY(); //calling parent class method
obj.methodZ(); //calling local method
}
}

You might also like