【问题标题】:new class from static method [duplicate]静态方法的新类[重复]
【发布时间】:2018-05-10 22:08:01
【问题描述】:

当我尝试从静态方法(在父类中)创建新类(在父类中定义的)时出现错误。

错误:非静态变量 this 不能从静态上下文中引用

public class ParentClass {
    public class ChildClass {
        ...
    }

    public void method () {
        // Compiles
        ChildClass childClass = new ChildClass();
    }

    public static void static_method () {
        // error: non-static variable this cannot be referenced from a static context
        ChildClass childClass = new ChildClass();
    }
}

当然,我可以将 ChildClass 类创建为新的单独类,但我不明白为什么这不起作用。

------- 编辑 -------

将内部类 (ChildClass) 设为静态将使该类作为单独的类 (source) 工作,因为它位于不同的类中,这正是我所需要的。

    public static class ChildClass {

------- 编辑#2 -------

只是为了说明非静态类,如在第一个代码示例中,当使用和从非静态方法(如 method() 中创建)时,可以访问和使用 ParentClass 的函数和变量。

【问题讨论】:

  • 内部类需要对外部包含类的引用;让它static。将public class ChildClass 更改为public static class ChildClass - 否则您将需要ParentClass 的实例。
  • @ElliottFrisch 如果您将评论转换为答案(并 ping 我),我保证会投赞成票。
  • @Elliott Frisch 感谢您的回答 - 效果很好。我的问题是我对静态类的含义有偏见。谢谢。

标签: java class static-methods


【解决方案1】:

子类不是静态类,因此不能在静态成员中使用。为了能够在静态成员中使用它,请将其设为静态:

public static class ChildClass {
        ...
}

【讨论】:

    猜你喜欢
    • 2016-06-05
    • 1970-01-01
    • 1970-01-01
    • 2014-01-10
    • 1970-01-01
    • 1970-01-01
    • 2011-05-29
    • 2020-08-06
    • 1970-01-01
    相关资源
    最近更新 更多