【问题标题】:how to resolve Non-Static method cannot be referenced from a static context?如何解决无法从静态上下文中引用非静态方法?
【发布时间】:2015-10-18 11:22:18
【问题描述】:
class Base {

    Base show() {
        System.out.println("Base");
        return new Base();
    }

    class Child4 extends Base {

        Child4 show() {
            System.out.println("Child4");
            return new Child4();
        }

    }

    public static void main(String... s) {
        Child4 C1 = new Child4();
        C1.show();
    }

}

【问题讨论】:

  • 嗨迪莎。欢迎来到堆栈溢出。请让您更容易理解您的问题:您对发布的代码有何尝试?您是否收到错误消息,或者代码的行为是否与您认为的不同?你认为它应该做什么,你观察到了什么行为?
  • 不要将 Child4 类嵌套到 Base 类中。使用 2 个不同的文件:每个类一个。

标签: java non-static


【解决方案1】:

在您的示例中,Child4 是类Base 的非静态内部类(有关内部类的文档,请参阅here)。这意味着您需要 Base 类的实例才能实例化 Child4 类的对象。

由于在您的示例中没有从 Child4 实例到外部 Base 实例的访问权限,因此似乎不打算使用非静态内部类。你应该声明这个内部类是静态的,用

static class Child4 extends Base {

这样,从main 静态上下文中对new Child4 的调用将是合法的。

【讨论】:

    【解决方案2】:

    你可以这样做:

    public static void main(String... s) { Base base= new Base(); Base.Child4 C1 = base.newChild4(); C1.show(); }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-31
      • 1970-01-01
      相关资源
      最近更新 更多