【问题标题】:Java Changing variables while instantiating an abstract classJava 在实例化抽象类时更改变量
【发布时间】:2016-02-19 01:34:26
【问题描述】:

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

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

有没有什么方法可以使用我正在尝试的方法来实现这一点?

【问题讨论】:

    标签: java class abstract


    【解决方案1】:

    你应该使用初始化块:

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

    【讨论】:

    • 似乎这就是答案。不过,我无法在几分钟内将您标记为解决方案。谢谢!
    【解决方案2】:
    public String testString = "test";
    

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

    试试:

    Super.testString = "test"; 
    

    从 Super 中更改 testString 的值。

    【讨论】:

      猜你喜欢
      • 2015-07-11
      • 2014-09-08
      • 1970-01-01
      • 2018-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-10
      相关资源
      最近更新 更多