最终变量和构造函数重载

问题描述 投票:1回答:3

我想在我的类中使用构造函数重载,我也想要定义一些最终变量。

我想要的结构是这样的:

public class MyClass{
    private final int variable;

    public MyClass(){
        /* some code and 
           other final variable declaration */
        variable = 0;
    }

    public MyClass(int value){
        this();
        variable = value;
    }
}

我想调用this()以避免在我的第一个构造函数中重写代码,但我已经定义了最终变量,因此这给出了编译错误。我想到的最方便的解决方案是避免使用final关键字,但当然这是最糟糕的解决方案。

在多个构造函数中定义变量并避免代码重复的最佳方法是什么?

java constructor final
3个回答
2
投票

你快到了。重写构造函数,使默认构造函数调用值为0的重载构造函数。

public class MyClass {
    private final int variable;

    public MyClass() {
        this(0);
    }

    public MyClass(int value) {
        variable = value;
    }

}

0
投票

如果您的数字变量较小,则可以使用Telescoping Constructor模式。 MyClass(){...} MyClass(int value1){...} Pizza(int value1,int value2,int value3){...}

                                                                                                If there is multiple variable and instead of using method overloading you can use builder pattern so you can make all variable final and will build object gradually.


public class Employee {
    private final int id;
    private final String name;

    private Employee(String name) {
        super();
        this.id = generateId();
        this.name = name;

    }

    private int generateId() {
        // Generate an id with some mechanism
        int id = 0;
        return id;
    }

    static public class Builder {
        private int id;
        private String name;

        public Builder() {
        }

        public Builder name(String name) {
            this.name = name;
            return this;
        }

        public Employee build() {
            Employee emp = new Employee(name);
            return emp;
        }
    }
}

0
投票

您不能在两个构造函数中分配final变量。如果你想保留final变量并且想要通过构造函数设置,那么你可以使用一个构造函数来设置最终变量,并且还包括类所需的公共代码功能。然后从像this(*finalVariableValue*);这样的另一个构造函数中调用它

© www.soinside.com 2019 - 2024. All rights reserved.