这个Java代码有什么错误吗?

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.您将无法直接访问其私有字段.

(注意那里的任何一个学生:是的,我知道我正在简化.)

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...