有人可以解释Java中的构造函数吗?

use*_*794 1 java constructor

我正在通过阅读在线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在构造函数中使用.有些人避免对参数和字段使用相同的名称,但我个人没有看到这个问题.
  • 我做了田地finalprivate; 字段应该几乎总是私有IMO,并尽可能最终 - 如果你可以使整个类型不可变,那就更好了.(这导致更具功能性的编程风格,更容易推理和测试.)
  • 我已经更改了参数的名称 - 名称将是饼干的名称,因此不需要在参数名称中指定,同样numOfBiscuits显然与饼干相关.

所有这些都有意义吗?如果你有问题,请问更多问题!

  • accessor = .getXX()mutator = .setXXX(value) (2认同)