gpt4 book ai didi

java - 这段Java代码有没有错误?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:04:23 26 4
gpt4 key购买 nike

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 是一个完全独立于您的 main 方法的类。在这种情况下,您只能通过 public 接口(interface)访问 Creature。您将无法直接访问其私有(private)字段。


(请注意那里的任何学究:是的,我知道我在简化。)

关于java - 这段Java代码有没有错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1649429/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com