gpt4 book ai didi

java - 最终属性在对象实例化后初始化

转载 作者:行者123 更新时间:2023-12-02 00:17:46 25 4
gpt4 key购买 nike

嗯,我有一个最终属性,但我不想在创建对象时初始化它,因为我不能。因此,我尝试不在构造函数中初始化它,而是使用 setter,我猜它会是一次性可用的 setter,但我遇到了此错误:

Test.java:27: error: cannot assign a value to final variable foo

    this.foo = new String(foo);

这是我用来测试这个的简短代码:

class Test {

private final String foo;

public static void main(String[] args) {
Test test = new Test();
test.setFoo("gygygy");
System.out.println(test.getFoo());
}

public Test() {
System.out.println("Constructor");
}

public String getFoo() {
return foo;
}

public void setFoo(String foo) {
this.foo = foo;
}

}

所以我假设构造函数隐式地生成了类似 this.foo = new String(); 的内容。或者 this.foo = null;我想我无法改变这种行为,但是我怎样才能拥有与我想做的事情相当的东西呢?我认为是这样的:

private String foo;

/* ... */

public void setFoo(String foo) {
if( !(this.foo.isInitialized()) )
this.foo = foo;
}

但是 Object.isInitialized() 方法显然不存在,而且我找不到等效的 x)

所以这是我的问题:我该怎么办?我想要一个最终属性在对象实例化时未初始化

谢谢!

最佳答案

您可以添加 boolean 字段isInisialized,但最好的选择是在构造函数中传递值(如果需要,可以使用构建器模式)

关于java - 最终属性在对象实例化后初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11602031/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com