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

Aru*_*lam 6 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);
   }
}
Run Code Online (Sandbox Code Playgroud)

这段代码有什么错误吗?

"other.yearOfBirth"错了吗?我的教师说这是错的,但它对我来说很好.

Gre*_*g D 7

正如你所发现的,它会起作用.不过,我怀疑在游戏中存在根本性的误解.

我的通灵能力告诉我,你的导师期望代码更像是以下内容:

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
   }
}
Run Code Online (Sandbox Code Playgroud)

误解是你只创建了一个类 - 你的主应用程序类.这有效地创建yearOfBirth了一种可以从main方法访问的混合全局值.在更典型的设计中,Creature是一个完全独立于主方法的类.在这种情况下,您只能Creature通过其public界面进行访问.您将无法直接访问其私有字段.


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

  • 是的,`yearOfBirth = other.yearOfBirth`确实有效,OO意识的教练可能希望你使用`other.getYearOfBirth()`方法. (2认同)

Wil*_*ill 5

你必须要求你的教师解释为什么他们认为这是错的(这可能是一种风格问题,甚至是一种误解),所以你可以从中学习.

最终这个人会影响你的成绩.这是与他们积极互动的绝佳机会.你的老师教你个人越多,你掌握主题的机会就越大.

另一方面,如果你被告知出了什么问题,你会私下离开并向一般的互联网社区询问,你可能会被告知你是对的,你最终会产生错误的优越感.你的老师会适得其反.

  • 把它看作是一种学习经历.是不是因为它没有编译?或者它是错的,因为虽然它编译,但是有一个问题.或者它是错的,因为它没有解决你被要求解决的问题?那里有大量的生产代码可供使用,但仍然是完全错误的! (3认同)