繁体   English   中英

最终变量和构造函数重载

[英]Final variable and Constructor Overloading

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

我想要的结构是这样的:

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关键字,但当然这是最糟糕的解决方案。

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

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

public class MyClass {
    private final int variable;

    public MyClass() {
        this(0);
    }

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

}

如果变量较小,那么可以使用伸缩构造函数模式。
MyClass(){...} MyClass(int value1){...}
披萨(int值1,int值2,int值3){...}

                                                                                                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变量。 如果要保留final变量,并且还希望通过构造函数进行设置,则有一种可能性,您将专用于一个构造函数来设置最终变量,并且还包括该类所需的通用代码功能。 然后从另一个类似this(*finalVariableValue*);构造函数中调用它this(*finalVariableValue*);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM