class Creature {
private int yearOfBirth=10;
public void setYearOfBirth(int year) {
yearOfBirth = year;
}
void setYearOfBirth(Creature other) {
yearOfBirth = other.yearOfBirth; // is this correct it compiles fine
}
int getYearOfBirth() {
return yearOfBirth;
}
public static void main(String args[])
{
Creature c = new Creature();
c.setYearOfBirth(89);
Creature d = new Creature();
c.setYearOfBirth(d);
System.out.println(c.yearOfBirth);
}
}
此代码中是否有任何错误?此Java代码中是否有任何错误?
“other.yearOfBirth”错了吗?我的老师说这是错误的,但它对我来说工作正常。
Upvoting(不知道为什么这是downvoted) - 这似乎是一个非常好的初学者级别的问题给我。 – paxdiablo 2009-10-30 12:17:55
你的老师指出你直接访问'private'变量'yearOfBirth',而不是'getYearOfBirth()'(JavaBean访问)。你能够这样做并且编译的唯一原因是因为'private'数据可以被同一类的任何实例访问。如果你试图直接从'NonCreature'类访问'yearOfBirth',编译器肯定会抛出一个错误,你将不得不使用'public'方法'getYearOfBirth()'。 – 2009-10-30 13:38:16