I am a first time user of Java swing and this is the first time I’m trying to use a private class.
I am trying the following code –
ActionListener listener = new AddButtonListener();
Where AddButtonListener is a private class that implements the ActionListener interface.
private class AddButtonListener implements ActionListener{
public void actionPerformed(ActionEvent e){
....
}
}
However, I am getting an eclipse error that reads
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).
Note that the class is being instantiated in a static main method inside someType.
Why is this error coming up? Is it because the main method is static?
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
If you are in some method in SomeType, then you would create an object of this non-static inner class as
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.
So, it’s not about the class being private, but about it not being static.