我正在通过阅读在线Java书籍学习Java,但我发现很难理解"构造函数".我的问题是如何编写一个构造函数,将类的私有字段设置为接收的值?
我试过这个,但不认为它是正确的:
public Biscuit(String id, String Biscuitname, int numOfBiscuits);
Run Code Online (Sandbox Code Playgroud)
因此,如果我有示例"12002消化83",我需要一个构造函数,将类的私有字段设置为接收到的这些值
希望这是有道理的
Jon*_*eet 15
干得好:
public class Biscuit
{
private final String id;
private final String name;
private final int count;
public Biscuit(String id, String name, int count)
{
this.id = id;
this.name = name;
this.count = count;
}
// Other code
}
Run Code Online (Sandbox Code Playgroud)
一些说明:
this.foo = foo在构造函数中使用.有些人避免对参数和字段使用相同的名称,但我个人没有看到这个问题.final和private; 字段应该几乎总是私有IMO,并尽可能最终 - 如果你可以使整个类型不可变,那就更好了.(这导致更具功能性的编程风格,更容易推理和测试.)numOfBiscuits显然与饼干相关.所有这些都有意义吗?如果你有问题,请问更多问题!