anandraiin3
BAN USERit's always preferable to use composition than inheritance , composition let's you to adapt more than one behaviour , you can inherit only one interface but you can inherit more than one using composition . By using method delegation you can provide virtual inheritance .
for example
public interface Aircraft {
fly();
takeoff();
land();
}
public interface Fighter{
fireBullets();
fireMissile();
}
Using inheritance
public class Plane implements aircraft {
fly()
{
//fly
}
takeoff()
{
//takeoff
}
land()
{
//land
}
}
public class F16 extends Plane implements Fighter
{
fireBullets()
{
//fire F16 Bullets
}
fireMissile()
{
//fire F16 laser guided missiles
}
}
Usage
F16 alpha = new F16();
alpha.takeoff();
alpha.fly();
alpha.fireBullets();
alpha.fireMissiles();
alpha.land();
Using Composition
public class F16
{
Plane myPlane;
Fighter myFighter;
F16(Plane myPlane, Fighter myFighter)
{
// assign
}
fly()
{
myPlane.fly();
}
// same kind of delegation for remaining methods
}
assuming boeing and m20gun are concrete implementations of plane and fighter
F16 alpha = new F16(boeing,m20gun);
alpha.takeoff();
alpha.fly();
alpha.fireBullets();
alpha.fireMissiles();
alpha.land();
pop()
- anandraiin3 April 07, 2009{
int n = counter ;
counter -- ;
return data[n];
}