Java 最终变量和构造函数重载

Java 最终变量和构造函数重载,java,constructor,final,Java,Constructor,Final,我想在我的类中使用构造函数重载,我还想定义一些最终的变量 我想要的结构是: public class MyClass{ private final int variable; public MyClass(){ /* some code and other final variable declaration */ variable = 0; } public MyClass(int value){

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

我想要的结构是:

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;
    }
}
我想调用它以避免在我的第一个构造函数中重写代码,但我已经定义了最后一个变量,因此这会导致编译错误。 我想到的最方便的解决方案是避免使用final关键字,但这当然是最糟糕的解决方案


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

您几乎做到了。重写构造函数,使默认构造函数调用值为0的重载构造函数

public class MyClass {
    private final int variable;

    public MyClass() {
        this(0);
    }

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

}

若你们有一个小的数字变量,那个么可以使用伸缩构造函数模式。 MyClass{…} MyClassint值1{…} Pizzaint 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;
        }
    }
}
不能在两个构造函数中都指定final变量。如果您希望保留最终变量,并且还希望通过构造函数进行设置,那么您可以指定一个构造函数来设置最终变量,并包括类所需的公共代码功能。然后从另一个构造函数调用它,比如*finalVariableValue*