Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible in Java to initialise a final data member based on constructor call?

Is it possible to make a modification as specified in the class below, and initialize a member for existing callers to some default value, say null?

Member is required to be private final as persistence requirement.

// initial version of the class
public class A {
    A() {
        // do some work here
    }
}

// the following modification required adding additional constructor to the class with **member** data member.
public class A {
    private final String member;

    A(String member) {
        this();
        this.member = member;   
    }

    A() {
        // initilize member to null if a client called this constructor
        // do some work here
    }
}
like image 723
Leonid Avatar asked Dec 22 '22 13:12

Leonid


1 Answers

Why can't you just have:

public class A {
    private final String member;

    A(String member) {
        this.member = member;   
    }

    A() {
        this(null);
    }
}

This is the usual pattern for constructor chaining; have the less-specific versions call the more-specific versions, supplying default parameters as appropriate.

like image 59
Oliver Charlesworth Avatar answered Apr 13 '23 08:04

Oliver Charlesworth