Java 中是否可以根据构造函数调用来初始化最终数据成员?

发布于 2024-11-14 00:51:49 字数 612 浏览 1 评论 0原文

是否可以按照下面的类中指定的方式进行修改,并将现有调用者的成员初始化为某个默认值,例如null

作为持久性要求,成员必须是私有最终

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

满身野味 2024-11-21 00:51:49

为什么你不能直接拥有:

public class A {
    private final String member;

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

    A() {
        this(null);
    }
}

这是构造函数链接的常见模式;让不太具体版本调用更具体版本,并根据需要提供默认参数。

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.

究竟谁懂我的在乎 2024-11-21 00:51:49

是的!

public class A {
    private final String member;

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

    A() {
        this(null);
    }
}

Yes!

public class A {
    private final String member;

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

    A() {
        this(null);
    }
}
旧城空念 2024-11-21 00:51:49

是的,这通常用在枚举中。

Yes, This is usually employed in Enums.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文