- 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);
- }
- }
“other.yearOfBirth”错了吗?我的教师说这是错的,但它对我来说很好.
解决方法
正如你所发现的,它会起作用.不过,我怀疑在游戏中存在根本性的误解.
- class Creature {
- private int yearOfBirth=10;
- public void setYearOfBirth(int year) {
- yearOfBirth = year;
- }
- public void setYearOfBirth(Creature other) {
- yearOfBirth = other.yearOfBirth;
- }
- public int getYearOfBirth() {
- return yearOfBirth;
- }
- }
- class Program {
- 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); // This will not compile
- }
- }
误解是你只创建了一个类 – 你的主应用程序类.这有效地使yearOfBirth成为您可以从main方法访问的混合全局值.在更典型的设计中,Creature是一个完全独立于主要方法的类.在这种情况下,您只能通过其公共接口访问Creature.您将无法直接访问其私有字段.
(注意那里的任何一个学生:是的,我知道我正在简化.)