这个Java代码有什么错误吗?
发布时间:2020-12-14 05:51:40 所属栏目: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() { r
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.您将无法直接访问其私有字段. (注意那里的任何一个学生:是的,我知道我正在简化.) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |