时间:2023-03-08 17:20:25
 //Java中的继承和组合之间的联系和区别
//本例是继承 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();
}
}
 //Java中的继承和组合之间的联系和区别
//本例是组合
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;
}
//重新定义一个自己的breath()方法
public void breath()
{
//直接复用Animal提供的breath()方法来实现Bird的breath()方法
a.breath();
}
public void fly()
{
System.out.println("我在天空自在的飞翔...");
}
}
class Wolf
{
//将原来的父类组合到子类中来,作为子类的一个组合部分.
private Animal a;
public Wolf(Animal a)
{
this.a = a;
}
//重新定义一个自己的breath()方法
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 a = new Animal();
Bird b = new Bird(a);
b.breath();
b.fly(); //此时需要显示创建被组合的对象
Animal a2 = new Animal();
Wolf w = new Wolf(a2);
w.breath();
w.run();
}
}