admin管理员组

文章数量:1584215

本文翻译自:Java - No enclosing instance of type Foo is accessible

I have the following code: 我有以下代码:

class Hello {
    class Thing {
        public int size;

        Thing() {
            size = 0;
        }
    }

    public static void main(String[] args) {
        Thing thing1 = new Thing();
        System.out.println("Hello, World!");
    }
}

I know Thing does nothing, but my Hello, World program compiles just fine without it. 我知道Thing不会执行任何操作,但是如果没有它,我的Hello,World程序可以正常编译。 It's only my defined classes that are failing on me. 只有我定义的类对我不利。

And it refuses to compile. 而且它拒绝编译。 I get No enclosing instance of type Hello is accessible." at the line that creates a new Thing. I'm guessing either: 在创建新的Thing的那一行中,我No enclosing instance of type Hello is accessible."看到No enclosing instance of type Hello is accessible."

  1. I have system level problems (either in DrJava or my Java install) or 我有系统级别的问题(在DrJava或Java安装中)或
  2. I have some basic misunderstanding of how to construct a working program in java. 我对如何在Java中构建工作程序有一些基本的误解。

Any ideas? 有任何想法吗?


#1楼

参考:https://stackoom/question/e79E/Java-无法访问类型为Foo的封闭实例


#2楼

Lets understand it with the following simple example. 让我们通过下面的简单示例来理解它。 This happens because this is NON-STATIC INNER CLASS. 发生这种情况是因为这是非静态内部类。 You should need the instance of outer class. 您应该需要外部类的实例。

 public class PQ {

    public static void main(String[] args) {

        // create dog object here
        Dog dog = new PQ().new Dog();
        //OR
        PQ pq = new PQ();
        Dog dog1 = pq.new Dog();
    }

    abstract class Animal {
        abstract void checkup();
    }

    class Dog extends Animal {
        @Override
        void checkup() {
            System.out.println("Dog checkup");

        }
    }

    class Cat extends Animal {
        @Override
        void checkup() {
            System.out.println("Cat Checkup");

        }
    }
}

#3楼

Well... so many good answers but i wanna to add more on it. 好吧...这么多好答案,但我想补充更多。 A brief look on Inner class in Java- Java allows us to define a class within another class and Being able to nest classes in this way has certain advantages: 对Java内部类的简要介绍-Java使我们能够在另一个类中定义一个类,并且能够以这种方式嵌套类具有某些优点:

  1. It can hide(It increases encapsulation) the class from other classes - especially relevant if the class is only being used by the class it is contained within. 它可以从其他类中隐藏(增加封装)该类-如果该类仅由包含在其中的类使用,则尤其相关。 In this case there is no need for the outside world to know about it. 在这种情况下,外界无需了解它。

  2. It can make code more maintainable as the classes are logically grouped together around where they are needed. 由于类在需要的地方按逻辑分组在一起,因此可以使代码更易于维护

  3. The inner class has access to the instance variables and methods of its containing class. 内部类可以访问其包含类的实例变量和方法。

We have mainly three types of Inner Classes 我们主要有三种类型的Inner Classes

  1. Local inner 局部内部
  2. Static Inner Class 静态内层
  3. Anonymous Inner Class 匿名内部阶层

Some of the important points to be remember 要记住的一些重要点

  • We need class object to access the Local Inner Class in which it exist. 我们需要类对象来访问它所在的本地内部类。
  • Static Inner Class get directly accessed same as like any other static method of the same class in which it is exists. 可以直接访问静态内部类,就像它所在的相同类的任何其他静态方法一样。
  • Anonymous Inner Class are not visible to out side world as well as to the other methods or classes of the same class(in which it is exist) and it is used on the point where it is declared. 匿名内部类对于外部世界以及同一个类(存在该类)的其他方法或类不可见,并且在声明该点时使用。

Let`s try to see the above concepts practically_ 让我们尝试实际了解以上概念_

public class MyInnerClass {

public static void main(String args[]) throws InterruptedException {
    // direct access to inner class method
    new MyInnerClass.StaticInnerClass().staticInnerClassMethod();

    // static inner class reference object
    StaticInnerClass staticInnerclass = new StaticInnerClass();
    staticInnerclass.staticInnerClassMethod();

    // access local inner class
    LocalInnerClass localInnerClass = new MyInnerClass().new LocalInnerClass();
    localInnerClass.localInnerClassMethod();

    /*
     * Pay attention to the opening curly braces and the fact that there's a
     * semicolon at the very end, once the anonymous class is created:
     */
    /*
     AnonymousClass anonymousClass = new AnonymousClass() {
         // your code goes here...

     };*/
 }

// static inner class
static class StaticInnerClass {
    public void staticInnerClassMethod() {
        System.out.println("Hay... from Static Inner class!");
    }
}

// local inner class
class LocalInnerClass {
    public void localInnerClassMethod() {
        System.out.println("Hay... from local Inner class!");
    }
 }

}

I hope this will helps to everyone. 希望对大家有帮助。 Please refer for more 请参考更多


#4楼

Thing is an inner class with an automatic connection to an instance of Hello . Thing是一个内部类 ,它具有与Hello实例的自动连接。 You get a compile error because there is no instance of Hello for it to attach to. 您会收到一个编译错误,因为没有Hello实例可以附加到该实例。 You can fix it most easily by changing it to a static nested class which has no connection: 通过将其更改为没有连接的静态嵌套类 ,可以最轻松地修复它:

static class Thing

#5楼

static class Thing will make your program work. static class Thing将使您的程序正常工作。

As it is, you've got Thing as an inner class, which (by definition) is associated with a particular instance of Hello (even if it never uses or refers to it), which means it's an error to say new Thing(); 实际上,您已经将Thing作为内部类,(根据定义)它与Hello的特定实例相关联(即使它从不使用或引用它),这意味着说new Thing();是错误的new Thing(); without having a particular Hello instance in scope. 范围内没有特定的Hello实例。

If you declare it as a static class instead, then it's a "nested" class, which doesn't need a particular Hello instance. 如果改为将其声明为静态类,则它是“嵌套”类,不需要特定的Hello实例。


#6楼

You've declared the class Thing as a non-static inner class. 您已将Thing类声明为非静态内部类。 That means it must be associated with an instance of the Hello class. 这意味着它必须与Hello类的实例相关联。

In your code, you're trying to create an instance of Thing from a static context. 在您的代码中,您尝试从静态上下文创建Thing的实例。 That is what the compiler is complaining about. 这就是编译器所抱怨的。

There are a few possible solutions. 有几种可能的解决方案。 Which solution to use depends on what you want to achieve. 使用哪种解决方案取决于您要实现的目标。

  • Move Thing out of the Hello class. Thing移出Hello类。

  • Change Thing to be a static nested class. Thing更改为static嵌套类。

     static class Thing 
  • Create an instance of Hello before creating an instance of Thing . 创建实例 Hello创建实例前Thing

     public static void main(String[] args) { Hello h = new Hello(); Thing thing1 = h.new Thing(); // hope this syntax is right, typing on the fly :P } 

The last solution (a non-static nested class) would be mandatory if any instance of Thing depended on an instance of Hello to be meaningful. 如果Thing任何实例都依赖Hello实例,那么最后一个解决方案( 非静态嵌套类)将是必需的。 For example, if we had: 例如,如果我们有:

public class Hello {
    public int enormous;

    public Hello(int n) {
        enormous = n;
    }

    public class Thing {
        public int size;

        public Thing(int m) {
            if (m > enormous)
                size = enormous;
            else
                size = m;
        }
    }
    ...
}

any raw attempt to create an object of class Thing , as in: 创建Thing类的对象的任何原始尝试,例如:

Thing t = new Thing(31);

would be problematic, since there wouldn't be an obvious enormous value to test 31 against it. 这将是有问题的,因为测试31并没有明显的enormous价值。 An instance h of the Hello outer class is necessary to provide this h.enormous value: Hello外部类的实例h对于提供此h.enormous值是必需的:

...
Hello h = new Hello(30);
...
Thing t = h.new Thing(31);
...

Because it doesn't mean a Thing if it doesn't have a Hello . 因为它没有Hello并不意味着Thing

For more information on nested/inner classes: Nested Classes (The Java Tutorials) 有关嵌套/内部类的更多信息: 嵌套类(Java教程)

本文标签: 实例无法访问类型JavaFoo