在构造函数中初始化私有变量

时间:2011-02-21 20:56:26

标签: java variables initialization

我一直在看这个代码用于比较器。我的问题是在构造函数中初始化两个私有变量有一个特定的好处(在默认构造函数中完成)。我知道第二个构造函数可用于创建具有提供值的实例。如果我这样做会有什么不同

private String sortBy = COLUMN_LAST_NAME;
private boolean ascending = true; 

如果它是一个真正简单而通用的问题,我道歉。

public class CustomComparator implements Comparator<StudentList>
{   private String sortBy;
private boolean ascending;

public CustomComparator()
{
    sortBy = COLUMN_LAST_NAME;
    ascending = true;
}

public CustomComparator(String sortBy, boolean ascending)
{
    this.sortBy = sortBy;
    this.ascending = ascending;
}

4 个答案:

答案 0 :(得分:6)

我见过的最佳实践是有一个构造函数,它接受所有参数,即使它意味着它必须是私有的,然后只需使用this(..,..,...)从其他构造函数调用它,同时提供适当的值。

这将使您尽可能多地重用代码,并且将来的修复只会转到一个地方和一个地方 - 无需对代码进行双重维护。

您的示例如下所示:

public class CustomComparator implements Comparator<StudentList> {
    private String sortBy;
    private boolean ascending;

    public CustomComparator()
    {
        this(COLUMN_LAST_NAME, true);
    }

    public CustomComparator(String sortBy, boolean ascending)
    {
        this.sortBy = sortBy;
        this.ascending = ascending;
    }
}

初始化通常被接受在构造函数中,以便更容易区分静态成员的静态初始化和实例变量的每个实例init。没有性能差异。

答案 1 :(得分:3)

实际上,如果你关心对象的不变性,那就很重要了(你应该:-))。如果您的两个字段均为final,则必须按以下方式对其进行初始化:

public class CustomComparator implements Comparator<StudentList> {
    private final String sortBy;
    private final boolean ascending;

    public CustomComparator() {
        sortBy = COLUMN_LAST_NAME;
        ascending = true;
    }

    public CustomComparator(String sortBy, boolean ascending) {
        this.sortBy = sortBy;
        this.ascending = ascending;
    }
}

甚至更好:

public class CustomComparator implements Comparator<StudentList> {
    private final String sortBy;
    private final boolean ascending;

    public CustomComparator() {
        this(COLUMN_LAST_NAME, true);
    }

    public CustomComparator(String sortBy, boolean ascending) {
        this.sortBy = sortBy;
        this.ascending = ascending;
    }
}

答案 2 :(得分:1)

所有关于你需要的东西,两个构造函数都是不错的选择,如果你想初始化字段是最好的选择,但想想你是否像Hibernate上的Entity一样使用这个类,或者像Spring框架上的bean那样使用它,如果你不要写空构造函数什么都不会运行正常...

如果您在DTO模式中思考,声明像@Tomasz Nurkiewicz这样的不可变字段然后说参数化构造函数是唯一的选择....

但就像我之前说的那样,这取决于重新征服......

答案 3 :(得分:0)

我想不出任何差异,我更喜欢在变量声明中初始化。