我正在尝试创建一个抽象类,在实例化该类的新对象时,我正在尝试在该类中设置一个变量。
abstract class TestClass { // Class I'm trying to change a variable in.
public String testString;
}
public class Main {
public static void main(String[] args) {
TestClass t = new TestClass() {
public String testString = "TEST"; // Where I'm trying to set it
};
System.out.println(t.testString);
}
}
输出:
null
我不希望它输出“TEST”。
有没有什么办法可以使用像我正在尝试做的那样的方法来实现这一目标?
最佳答案
你应该使用初始化 block :
TestClass t = new TestClass() {
{ // initializer block
testString = "TEST";
}
};
关于Java在实例化抽象类时更改变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35495760/