简体   繁体   中英

Final variable and Constructor Overloading

I want to use Constructor Overloading in my class and I also would like to have some final variables to define.

The structure I would like to have is this:

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;
    }
}

I would like to call this() to avoid to rewrite the code in my first constructor but I have already defined the final variable so this give a compilation error. The most convenient solution I have in mind is to avoid the final keyword but of course it is the worst solution.

What can be the best way to define the variable in multiple constructors and avoid code repetitions?

You are almost there. Rewrite your constructors such way that your default constructor call the overloaded constructor with value 0.

public class MyClass {
    private final int variable;

    public MyClass() {
        this(0);
    }

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

}

If you have small number variable then it is ok to use Telescoping Constructor pattern.
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;
        }
    }
}

You can not assign final variable in both constructors. If you want to keep the final variable and also want to set via constructor then one possibility that you will dedicate one constructor to set the final variable and also include common code functionality needed by the class. Then call this from another constructor like this(*finalVariableValue*);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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