我有以下 Java 代码:
public interface Person {
int eat (String food);
int sleep (int time);
boolean coitus (person partner);
}
public class Citizen implements Person {
private int passion;
private int morality;
private String party;
public citizen () {
passion = 0;
morality = 100;
party = "Democrat";
}
public boolean coitus (person partner) {
passion += 10;
morality -= 10;
return true;
}
... rest of implementation methods
}
在主要方法中,我有以下几行:
Person Jon = new Citizen();
System.out.println(Jon.party);
第二行失败。我无法通过接口访问子类的变量。为什么是这样?我们可以用方法很好地做到这一点:
Person Jon = new Citizen();
Person Romney = new Citizen();
System.out.println(Jon.coitus(Romney));
上面三行工作得很好——换句话说,接口的方法是动态的。为什么它与变量不一样,有没有办法解决这个问题?