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

前端之家收集整理的这篇文章主要介绍了这个Java代码有什么错误吗?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. class Creature {
  2. private int yearOfBirth=10;
  3.  
  4. public void setYearOfBirth(int year) {
  5. yearOfBirth = year;
  6. }
  7.  
  8. void setYearOfBirth(Creature other) {
  9. yearOfBirth = other.yearOfBirth; // is this correct it compiles fine
  10. }
  11.  
  12. int getYearOfBirth() {
  13. return yearOfBirth;
  14. }
  15.  
  16. public static void main(String args[])
  17. {
  18. Creature c = new Creature();
  19. c.setYearOfBirth(89);
  20.  
  21. Creature d = new Creature();
  22. c.setYearOfBirth(d);
  23.  
  24. System.out.println(c.yearOfBirth);
  25. }
  26. }

这段代码有什么错误吗?

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

解决方法

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

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

  1. class Creature {
  2. private int yearOfBirth=10;
  3.  
  4. public void setYearOfBirth(int year) {
  5. yearOfBirth = year;
  6. }
  7.  
  8. public void setYearOfBirth(Creature other) {
  9. yearOfBirth = other.yearOfBirth;
  10. }
  11.  
  12. public int getYearOfBirth() {
  13. return yearOfBirth;
  14. }
  15. }
  16.  
  17. class Program {
  18. public static void main(String args[]) {
  19. Creature c = new Creature();
  20. c.setYearOfBirth(89);
  21.  
  22. Creature d = new Creature();
  23. c.setYearOfBirth(d);
  24.  
  25. System.out.println(c.yearOfBirth); // This will not compile
  26. }
  27. }

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

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

猜你在找的Java相关文章