无法实例化私有类

pra*_*432 0 java swing jbutton actionlistener

我是Java swing的第一次用户,这是我第一次尝试使用私有类.

我正在尝试以下代码 -

ActionListener listener = new AddButtonListener();
Run Code Online (Sandbox Code Playgroud)

其中AddButtonListener是实现ActionListener接口的私有类.

private class AddButtonListener implements ActionListener{
  public void actionPerformed(ActionEvent e){
  ....
  }
}
Run Code Online (Sandbox Code Playgroud)

但是,我收到了一个读取的eclipse错误

不能访问someType类型的封闭实例.必须使用someType类型的封闭实例限定分配(egxnew A(),其中x是someType的实例).

请注意,该类正在someType中的静态main方法中实例化.

为什么会出现这个错误?是因为主要方法是静态的吗?

Vik*_*dor 5

Since AddButtonListener is an inner class and is not static, it can be instantiated only using an object of outer class.

For example, if your AddButtonListener class is defined in SomeType, then

SomeType obj = new SomeType();

SomeType.AddButtonListener listener = obj.new AddButtonListener();
Run Code Online (Sandbox Code Playgroud)

If you are in some method in SomeType, then you would create an object of this non-static inner class as

AddButtonListener listener = this.new AddButtonListener();
Run Code Online (Sandbox Code Playgroud)

If you want to create an instance of AddButtonListener without using an instance of SomeType (enclosing type), then you should mark AddButtonListener as static class.

private static class AddButtonListener implementsActionListener{
    public void actionPerformed(ActionEvent e){
        ....
    }
}
Run Code Online (Sandbox Code Playgroud)

So, it's not about the class being private, but about it not being static.