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

故事扮演 提交于 2019-12-10 16:28:37

问题


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

回答1:


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.




回答2:


Yes!

public class A {
    private final String member;

    A(String member) {
        this.member = member;
        // do some work here instead   
    }

    A() {
        this(null);
    }
}



回答3:


Yes, This is usually employed in Enums.



来源:https://stackoverflow.com/questions/6225667/is-it-possible-in-java-to-initialise-a-final-data-member-based-on-constructor-ca

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!