Reputation: 462
Here's a simple case:
private final MouseAdapter mouse = new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
calculate();
}
};
It's a class level field, so calling it an Anonymous Class doesn't seem right. None of the other names or descriptions in the Oracle Tutorials page on Nested Classes seemed to fit either.
I'm guessing it's something along the lines of "Single Use Object" but I'm having a hard time even describing it without saying something like "Class Level Named Anonymous Class"
For those not familiar with Java and AWT, I'm making an instance of a class that has no-operation methods to implement an interface for listening to mouse actions. I want an actual instance so I can add it as multiple types of listeners (wheel, motion, and click) but use the same object for control. The question itself is not AWT specific though.
Upvotes: 2
Views: 61
Reputation: 22972
Agree with kocko's
answer but want to add one thing which is ,
Anonymous classes are expressions, which means that you define the class in another expression.
So no matter where you declare it,it will remain anonymous class and no need to name your declaration differently. :)
Upvotes: 1
Reputation: 25950
It is an instance of an anonymous class, there's no need to find a new name for this.
From Oracle docs :
Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.
It does not say the instance is to be used only once, but only the class, so there is no contradiction with your case.
Upvotes: 2
Reputation: 62864
Let's split it in pieces
private final MouseAdapter mouse
is called a class member, which type (MouseAdapter
) denotes that the member can refer to instances and/or sub-classes of MouseAdapter
.
new MouseAdapter() { ... }
is called an anonymous implementation of the MouseAdapter
interface/abstract class.
So, to summarize: the class member mouse
holds a reference to an anonymous implementation of the MouseAdapter
interface/abstract class.
Upvotes: 4