JAVA - 组合的例子

class Animal
{
	private void beat()
	{
		System.out.println("Heart beat.");
	}
	public void breath()
	{
		beat();
		System.out.println("Breath...");
	}
}

class Bird
{
	private Animal a;
	public Bird(Animal a)
	{
		this.a = a;
	}
	public void breath()
	{
		a.breath();
	}
	public void fly()
	{
		System.out.println("I'm flying...");
	}
}

class Wolf
{
	private Animal a;
	public Wolf(Animal a)
	{
		this.a = a;
	}
	public void breath()
	{
		a.breath();
	}
	public void run()
	{
		System.out.println("I'm running...");
	}
}

public class SubClass
{
	public static void main(String[] args)
	{
		Animal al = new Animal();
		Bird b = new Bird(al);
		b.breath();
		b.fly();
		
		Wolf w = new Wolf(al);
		w.breath();
		w.run();
	}
}


你可能感兴趣的:(java)