Saturday, September 1, 2012

Inheritance in Object Orient Programming and Java


Inheritance
Its a process where one object acquire properites another.
Inheritence reduces the code re-usablity.

Inheritence can be achieved by using extends or implemnts keyword

Single Inheritance:
Class A extends B{
statements
}

Example:
=============
Pulsar is subclass of Bike
TVS is subclass of Bike.

package com.oops;

class TwoWheeler{

int count=1;

public void setProp(){
System.out.println("Color: Red & Brand:Own");
}

}
public class SingleInheritence extends TwoWheeler {

public static void main(String args[]){
TwoWheeler two=new TwoWheeler();
SingleInheritence si=new SingleInheritence();

System.out.println(si instanceof TwoWheeler);
System.out.println("Calling method in SuperClass");
si.setProp();
}
}

Output
=======
true
Calling method in SuperClass
Color: Red & Brand:Own

Multiple Inheritance can be acheived by using interface. 

Interface in Java Language (Click on link to know about interfaces)

Below example contains Single Inheritance and Multiple Inheritance Using Interfaces.

package com.oops;

class TwoWheeler{

int count=1;

public void setProp(){
System.out.println("Color: Red & Brand:Own");
}

}

interface Car
{
   public void setBrandname(String name);
}

interface HeaveyVechile{

public void setProperites(String prop);
}

public class Wheeler extends TwoWheeler implements Car, HeaveyVechile{


public static void main(String args[]){

TwoWheeler two=new TwoWheeler();
Wheeler si=new Wheeler();

System.out.println(si instanceof TwoWheeler);
System.out.println("Calling method in SuperClass");
si.setProp();
si.setBrandname("First");
si.setProperites("HeavyLoadVechile");
}

@Override
public void setBrandname(String name) {
System.out.println("Brand name is"+name);

}

@Override
public void setProperites(String prop) {
System.out.println("Heavy Vechile with 4 or 8 Wheels "+prop);


}

}

Output
=========
true
Calling method in SuperClass
Color: Red & Brand:Own
Brand name isFirst
Heavy Vechile with 4 or 8 Wheels HeavyLoadVechile

No comments:

Post a Comment

Thanks for your valuable comments