Total Pageviews

Thursday, 30 June 2011

INHERITANCE

Inheritance is one of the basic concept of OOP paradigm.It helps us to reuse the resources that already exist, instead of creating them again and again.So we can say that, Inheritance is a mechanism of deriving new class from old class. The old class is known as the parent class , base class or super class and the new class obtained is known as child class or derived class.
There are four types of inheritance.
*single inheritance : only one super class.
*multilevel inheritance : derived from derived class
*multiple inheritance : more than one super class
*hierarchical inheritance : one super class and more than one derived classes.



             
In java , multiple inheritance is possible only with the help of interface
.We will discuss interface latter.

syntax :
class subclass_name extends super_class{
variable of the class;
methods of the class;
}

extends is a keyword ,which signifies that the propertise of the superclass_name is extended to subclass_name.

//example of inheritance
class employee{
public int emplono , basic ;
public employee(int x, int y){
emplono = x;
 basic = y;
 }
public void getdata(){
System.out.println(" Employee number : " + emplono );
System.out.println("basic : " + basic );}
}       
class total extends employee
{
    int days;
total(int x, int y, int z){       
super(x, y);
days = z;}
public int salary (){
return basic*days;   
}
}
class hiha{
public static void main(String args[]){

total a2 = new total(123,500,25);
a2.getdata();
int z = a2.salary();
System.out.println(" salary : " + z);
}}

super keyword
In java , there is a keyword called as super. Super keyword helps us in two ways , first to call the constructor of the super class.Second it helps the sub classes to access the private(access modifier) data members of the super class.The sub class cannot directly access the variables or other data members that are defined as private (access modifier) in the super class.
In the above program , " super(x, y); " is used to pass arguments in the superclass's constructor employee.

//example: to access the superclass
class start {
 int i;
}
class der extends start {
public  int i;
public  der(int x, int y){
  super.i = x;
  i = y;
}
public int area (){
return super.i*i;
}}

class star{
    public static void main(String args[]){
   der a1 = new der(12,5);
  int z = a1.show();
  System.out.println(" area of rectangle : " + z );

    }
}

No comments:

Post a Comment