小明喜欢乐器, 如果他有3万块钱,他就买一架钢琴 如果他有8000块钱,他就买一部吉他, 如果他还不到1000,就先买个口琴。 元旦晚会,他将使用自己的乐器演奏。 试用多态模拟此过程。

package choose;
public class Xiaoming {
private double money;
private Xiaoming xiaoming;

public Xiaoming() {
	
}
public Xiaoming(double money) {
	this.money = money;	
}
public void setMoney(double money) {
	this.money = money;
}
public void buy() {
	if(money > 30000) {
		xiaoming = new Piano();
	}else if(money > 8000) {
		xiaoming = new Guitar();		
	}else if(money < 1000) {
		xiaoming = new Harmonica();
	}
}
public void play() {
	xiaoming.play();
}
}
package choose;

public class Tests {
	public static void main(String[] args) {
		Xiaoming xiaoming=new Xiaoming();
		xiaoming.setMoney(50000);
		xiaoming.buy();
		xiaoming.play();
	}
}
package choose;

public class Piano extends Xiaoming{

	public void play() {
		System.out.println("钢琴在演奏。。。");
	}
}
package choose;

public class Harmonica extends Xiaoming{
	public void play() {
		System.out.println("口琴在演奏。。。");
	}

}
package choose;

public class Guitar extends Xiaoming {
	
	public void play() {
		System.out.println("吉他在演奏。。。。");
	}

}
上一篇:变量与方法


下一篇:struct的使用