2017-2018春季学期《面向对象程序设计》
----------------------------------------
问题描述:
金库被盗,有3嫌犯名唤GoodMan, NiceMan和EvilMan. 今阿凡提将3根等长木棍分别交予3嫌犯,令3人携木棍睡一夜。是夜,罪犯EvilMan心虚畏罪将木棍削掉一截。次日天明,阿凡提令3人取木棍视之,GoodMan与NiceMan二木棍等长,独EvilMan之木棍短。阿凡提宣布EvilMan为罪犯,EvilMan服罪。
----------------------------------------
类设计:
嫌犯类(Suspect),罪犯类(Criminal),阿凡提类(Afanti)。
罪犯类与嫌犯类属性(name, stick)和部分(setStick(), getStick())方法相同,仅sleep()方法不同,故罪犯类继承嫌犯类,利用多态性重载sleep()方法。
在整个故事中,阿凡提是组织者,将main函数入口定义在阿凡提类中。
注意:一个java文件只能有一个public类
----------------------------------------
代码实现:
project:D:\eclipse_workspace\Afanti
package: advanced
src: Afanti.java Suspect.java Criminal.java
Afanti.java
package advanced;
import java.util.Vector;
public class Afanti {
public static void main(String args[])
{
Vector<Suspect> allSuspect = new Vector<Suspect>();
Suspect man0 = new Suspect("GoodMan");
Suspect man1 = new Suspect("NiceMan");
Criminal man2 = new Criminal("EvilMan");
allSuspect.add(man0);
allSuspect.add(man1);
allSuspect.add(man2);
Afanti afanti = new Afanti();
afanti.judge(allSuspect);
}
public void judge(Vector<Suspect> suspects)
{
int stick = 10;
for (Suspect man:suspects)
{
man.setStick(stick);
man.sleep();
}
for (Suspect man:suspects)
{
if(man.getStick() < stick)
{
System.out.println("Afanti: " + man.name + " is the Criminal!");
}
}
}
}
Suspect.java
package advanced;
public class Suspect {
public String name;
private int myStick;
public Suspect(String s)
{
name = s;
}
public int getStick()
{
return myStick;
}
public void setStick(int n)
{
myStick = n;
}
public void sleep()
{
System.out.println(name+" have a sleep");
}
}
Criminal.java
package advanced;
public class Criminal extends Suspect{
public Criminal(String s)
{
super(s);
}
// 多态性,重载sleep()函数
public void sleep()
{
System.out.println(name + " have a sleep");
System.out.println(name + " is scared");
int myStick = this.getStick();
myStick --;
this.setStick(myStick);
}
}
----------------------------------------
结果输出:
GoodMan have a sleep
NiceMan have a sleep
EvilMan have a sleep
EvilMan is scared
Afanti: EvilMan is the Criminal!