gpt4 book ai didi

java - 无法实例化私有(private)类

转载 作者:行者123 更新时间:2023-12-01 06:55:34 27 4
gpt4 key购买 nike

我是 Java swing 的首次用户,这是我第一次尝试使用私有(private)类。

我正在尝试以下代码 -

ActionListener listener = new AddButtonListener();

其中AddButtonListener是实现ActionListener接口(interface)的私有(private)类。

private class AddButtonListener implements ActionListener{
public void actionPerformed(ActionEvent e){
....
}
}

但是,我收到一个 Eclipse 错误,内容为

No enclosing instance of type someType is accessible. Must qualify the allocation with an enclosing instance of type someType (e.g. x.new A() where x is an instance of someType).

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

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

最佳答案

由于AddButtonListener是一个内部类并且不是静态的,因此只能使用外部类的对象来实例化它。

例如,如果您的 AddButtonListener 类是在 SomeType 中定义的,则

SomeType obj = new SomeType();

SomeType.AddButtonListener listener = obj.new AddButtonListener();

如果您使用 SomeType 中的某个方法,那么您将创建此非静态内部类的对象,如下所示

AddButtonListener listener = this.new AddButtonListener();

如果您想创建 AddButtonListener 的实例而不使用 SomeType(封闭类型)的实例,那么您应该将 AddButtonListener 标记为静态类。

private static class AddButtonListener implementsActionListener{
public void actionPerformed(ActionEvent e){
....
}
}

所以,这不是关于类是私有(private)的,而是关于它不是静态的。

关于java - 无法实例化私有(private)类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12994750/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com