继承与组合:继承是实现软件复用的重要手段,但继承会破坏封装性。组合也是是实现软件复用的方式,且可以提供更好的封装性。
//继承方法实现复用程序代码
class Animal
{
private void beat()
{
System.out.println("心脏跳动");
}
public void breath()
{
beat();
System.out.println("呼吸中----");
}
}
//继承Animal类,直接复用父类的breath方法
class Bird extends Animal
{
public void fly()
{
System.out.println("自由的飞翔");
}
}
//继承Animal类,直接复用父类的breath
class Wolf extends Animal
{
public void run()
{
System.out.println("跑跑跑跑跑");
}
}
public class InheritTest
{
public static void main(String[] args)
{
Bird b = new Bird();
b.breath();//继承,直接使用父类的方法
b.fly();//自己的方法
Wolf w = new Wolf();
w.breath();//继承,直接使用父类的方法
w.run();//自己的而方法
}
}
组合实现类复用
//组合实现复用代码
class Animal
{
private void beat()
{
System.out.println("心脏跳动");
}
public void breath()
{
beat();
System.out.println("呼吸中----");
}
}
//将原来的父类组合到子类,作为子类的一个组合部分
class Bird
{
private Animal a;
public Bird(Animal a)
{
this.a=a;
}
public void breath()
{
//直接复用Animal提供的breath()方法来实现Bird的breath()方法
a.breath();
}
public void fly()
{
System.out.println("自由的飞翔");
}
}
//将原来的父类组合到子类,作为子类的一个组合部分
class Wolf extends Animal
{
private Animal a;
public Wolf(Animal a)
{
this.a=a;
}
//重新定义一个自己的bretath()方法
public void breath()
{
//直接复用Animal提供的breath()方法来实现Bird的breath()方法
a.breath();
}
public void run()
{
System.out.println("跑跑跑跑跑");
}
}
public class CompositeTest
{
public static void main(String[] args)
{
//此时需要显示创建被组合的对象
Animal al =new Animal();
Bird b = new Bird(al);
b.breath();//继承,直接使用父类的方法
b.fly();//自己的方法
Animal a2 = new Animal();
Wolf w = new Wolf(a2);
w.breath();//继承,直接使用父类的方法
w.run();//自己的而方法
}
}