为什么我在Java内部类中出错?

问题描述 投票:-2回答:2

(1)。当我将方法声明为静态,然后使用内部类时对象我遇到以下错误。

不能从静态上下文中引用非静态变量。

(2)。但是当我使用方法声明为实例时,程序就会运行成功。

class Test   {
       public static void main(String[] args) {
          A.show();
       }
}
class A  {
      static void show() {
         B ref = new B();
         System.out.println(ref.x);
      }
      class B {
         int x = 10;
      }
}

(3)。但是当我再次将方法声明为静态并定义此对象时然后程序运行没有任何问题。

static void show() {
      B ref = new A().new B();
      System.out.println(ref.x);
}

为什么我在上述第一个提示中出现错误,而不是在第三点中。

java inner-classes
2个回答
0
投票

您不能执行以下操作:

class A  {
      static void show() {
         B ref = new B(); // <- problem is here
         System.out.println(ref.x);
      }
      class B {
         int x = 10;
      }
}

为了创建B的实例,您需要在A方法的类instance内进行操作,或创建封闭类(class A)的实例并使用它。

您的其他方法

static void show() {
      B ref = new A().new B();
      System.out.println(ref.x);
}

就是这样。新的A()创建一个A的实例,该实例又创建一个B的实例。如果要执行以下B ref = new B(),则需要将B类声明为static。但是,那么您可能还有其他问题需要解决。

查看讨论此问题的Java Tutorials


0
投票

让我们考虑以下示例:

public class Laptop {
    public static void main(String[] args) {
        Laptop.doThis(); //this will throw error
        new Laptop().doThis(); // this will not throw error

        InnerClass innerClass = new InnerClass(); //same as above you cannot call a non-static class from a static method
        System.out.println(innerClass.x);
    }

    void doThis()
    {
        System.out.println("Something");
    }

    class InnerClass
    {
        int x=10;
    }
}

doThis()方法本质上是非静态的,无法从静态方法访问,并且与类相同。

您可以参考以下资源:

https://www.geeksforgeeks.org/inner-class-java/

https://www.geeksforgeeks.org/static-keyword-java/

© www.soinside.com 2019 - 2024. All rights reserved.