Tuesday, 21 January 2014

INHERITANCE BASICS

Basics of Inheritance in java

How to use extends keyword to inherit the super class

Inheritance is one of the key feature of Object Oriented Programming.There are three types of inheritance in java,they are Single Inheritance,Multilevel Inheritance and Hierarchical Inheritance.Inheritance provided mechanism that allowed a class to inherit property of another class.When a class extends another class it inherits all non-private members including fields and methods.For class inheritance, Java uses the keyword extends.


Use extends keyword to inherit the super class:

class A
{
//properties and methods of A
}
class B extends A
 
{
}

Example:

class Employee
{  
 float salary=40000;  
}  
  
class Programmer extends Employee
{  
 int bonus=10000;  
    
 public static void main(String args[])
{  
   Programmer p=new Programmer();  
   System.out.println("Programmer salary is:"+p.salary);  
   System.out.println("Bonus of Programmer is:"+p.bonus);  
}  
}  

Output:
Programmer salary is:40000.0
Bonus of programmer is:10000

Disadvantages of Inheritance:
  • Both classes (super and sub classes) are tightly-coupled.
  • As they are tightly coupled (blinded each other strongly with extends keyword), they cannot work independently of each other.
  • Changing the code in super class method also affects the subclass functionality.
  • If super class method is deleted, the code may not work as subclass may call the super class method with super keyword. Now subclass method behaves independently.


Basics of inheritance in java


1 comment :

  1. well explanied and presented thanks
    redhat training in chennai | VMware training in chennai | linux training in chennai

    ReplyDelete