Friday, 12 July 2013

Inheritance in java

In Java there are 5 types of inheritance as follows
1). Single Inheritance
2). Multilevel Inheritance
3). Multiple Inheritance[achieved using Interface]
4). Hierarchical Inheritance
5). Hybrid Inheritance

 Before starting i would like explain few terms which we will using below. They are as follows
*Super Class is nothing but a Parent class or Base Class
*Sub Class is nothing but a Child Class which is inherited form the Parent Class

 1). Single Inheritance
In this type of Inheritance there will be only one super class and only one sub class will be involved
let us assume A is super class and B is sub class of A

A
B

Here Class B is inherited from Class A. This type of inheritance is named as Single Inheritance.

2). Multilevel Inheritance
In this type of Inheritance the super class is inherited by its sub class and this sub class will be inherited by the another sub class. let us assume A is super class and B is sub class of A and C is sub class B

A
B
C


Here Class C is inherited form Class B and this Class B is inherited form its parent class A. This type of inheritance is named as Multilevel Inheritance.

3). Multiple Inheritance
In this type of Inheritance the super class is inherited by its sub class and this sub class will be inherited by the another sub class. let us assume A is super class and B is also a super class and C is sub class of A & B

A  B
  ↓
C

Note: Multiple Inheritance is not supported by Java, where the possible way to achieve this can be done using Interface 

4). Hierarchical Inheritance
In this type of Inheritance there will be only one super class which is inherited by many sub class. let us assume A is super class and B and C are sub class of A.


A
  ↓
C


5). Hybrid Inheritance
 All the above type of Inheritance combination is mixed together to build a Hybrid Inheritance. It could be

A
↓  ↓
B  D E F
 
G

These are the different types of Inheritance in java




Access Specifier in java

This table tells you which other classes can see your classes data members and member methods when you use access specifiers

private default protected public
Same Class
Same Package
Subclass
Same Package
Non-Subclass
Different Package
Subclass

Note: Using Child refernce
Different Package
Non-Subclass