微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

原文地址:https://www.jb51.cc/java/121041.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐