Java 在实例化抽象时更改变量 class

Java Changing variables while instantiating an abstract class

我正在尝试创建一个抽象 class,并且在实例化该 class 的新对象时,我正在尝试在 class 中设置一个变量].

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"。

是否有任何方法可以使用像我正在尝试做的那样的方法来实现这一目标?

你应该使用初始化块:

TestClass t = new TestClass() {
    { // initializer block
        testString = "TEST";
    }
};
public String testString = "test";

在 Main 的主函数中创建一个变量,该变量与您要更改的变量是分开的。

尝试:

Super.testString = "test"; 

从 Super.

更改 testString 的值