Java 需要包含 <my reference> 的封闭实例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4297857/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 15:32:28  来源:igfitidea点击:

An enclosing instance that contains <my reference> is required

javainstance

提问by jason m

An enclosing instance that contains is required

需要一个包含的封闭实例

Below is the code. positionObjis the object that I am trying to use and it is giving me the above error.

下面是代码。positionObj是我尝试使用的对象,它给了我上述错误。

It's unclear why.

目前还不清楚原因。

package toolBox;
import toolBox.Secretary.positionObj;    

public class PositionManagement {
    public static HashMap<String, Secretary.positionObj> main(String vArg){
        positionObj newPosition=new positionObj();
    }
}

采纳答案by SLaks

You're trying to use the non-static inner positionObjclass without an instance of Secretaryfor it to belong to.
A non-static inner class must belong to an instance of its parent class

您正在尝试使用非静态内部positionObj类而没有Secretary它所属的实例。
非静态内部类必须属于其父类的实例

You should probably change positionObjto a normal class or a static inner class.

您可能应该更改positionObj为普通类或静态内部类。

Alternatively, you can write someSecretary.new positionObj()to create an instance of the inner class that belongs to the someSecretaryinstance.

或者,您可以编写someSecretary.new positionObj()以创建属于该someSecretary实例的内部类的实例。

回答by hvgotcodes

The correct generic signature would be

正确的通用签名是

public static HashMap<String, positionObj> main(String vArg)

you dont need to qualify positionObj since you already import it.

您不需要限定 positionObj,因为您已经导入了它。

However, I am pretty sure a main method must conform to the signature below. If you intend to have main be the main method for your program, change the signature to

但是,我很确定主方法必须符合下面的签名。如果您打算让 main 成为您程序的主要方法,请将签名更改为

 public static void main(String[] args) {...}

you can create a separate static method that returns a Map and invoke it from main.

您可以创建一个单独的静态方法,该方法返回一个 Map 并从 main 调用它。

As a note, all classes should begin with a capital letter, positionObj, should be PositionObj.

请注意,所有类都应以大写字母 positionObj 开头,应为 PositionObj。

回答by Teshan

First create an object of Outer class. In this case I think "Secretary". Then create positionObj. Like this,

首先创建一个外部类的对象。在这种情况下,我认为“秘书”。然后创建 positionObj。像这样,

Secretary x = new Secretary();
Secretary.positionObj y = x.new positionObj();