简体   繁体   English

无法实例化内部类

[英]Trouble instantiating inner class

I'm learning how to use inner classes, but I'm encountering a troubling error when I try to compile it. 我正在学习如何使用内部类,但是在尝试编译内部类时遇到麻烦的错误。 I'm trying to see how inner and outer classes can use one another's variables and methods. 我正在尝试查看内部类和外部类如何使用彼此的变量和方法。

When I try to compile this code it says: 当我尝试编译此代码时,它说:

.../src/MyOuter.java:39: non-static variable inner cannot 
be referenced from a static context

Code: 码:

public class MyOuter{
    private int x;

    public MyInner inner = new MyInner();

    public int getOuterX(){
        return x;
    }
    private void doStuff(){
        inner.go();
    }

    class MyInner{
        public int getInnerX(){
            return x;
        }
        void go(){
            x = 42;
        }
    }
    public static void main(String[] args) {
        MyOuter outer = new MyOuter();
        outer.doStuff();
        System.out.println("outer.x = " + outer.getOuterX());
        System.out.println("inner.x = " + inner.getInnerX());

    }
}

Thanks in advance for the help! 先谢谢您的帮助!

Since getInnerX() method is defined in MyInner class. 由于getInnerX()方法是在MyInner类中定义的。 You can't access it directly without the object of MyInner class .So change the line 如果没有MyInner类的对象,则无法直接访问它。

 System.out.println("inner.x = " + inner.getInnerX());  

to

System.out.println("inner.x = " + outer.inner.getInnerX());

As was said, you first need to extract the inner variable before referencing it the static main method. 如前所述,您首先需要提取inner变量,然后再将其引用为static main方法。 Try something like the following: 尝试如下操作:

{
    public static void main(String[] args) {
    MyOuter outer = new MyOuter();
    MyInner inner = outer.inner;
    outer.doStuff();
    System.out.println("outer.x = " + outer.getOuterX());
    System.out.println("inner.x = " + inner.getInnerX());
}

From Understanding Instance and Class Members : 通过了解实例成员和类成员

Fields that have the static modifier in their declaration are called static fields or class variables. 在声明中具有static修饰符的字段称为静态字段或类变量。 They are associated with the class, rather than with any object. 它们与类关联,而不与任何对象关联。 Every instance of the class shares a class variable, which is in one fixed location in memory. 该类的每个实例共享一个类变量,该变量位于内存中的一个固定位置。 Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class. 任何对象都可以更改类变量的值,但是也可以在不创建类实例的情况下操纵类变量。

Since your inner variable is associated with an object, it cannot be referenced like a static variable might be. 由于内部变量与对象相关联,因此无法像静态变量那样引用它。 Were it static, it would be shared between all instance of 'MyOuter' and would be accessible in the manner you have tried there. 如果它是静态的,它将在“ MyOuter”的所有实例之间共享,并且可以按照您在其中尝试的方式进行访问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM