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.
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.
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.
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. :)
Related
I often see people write inner classes for listeners take swing for example.
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//some action
}
});
At my uni there is a lot of emphasis on designs being decoupled using design patterns such as MCV or MVP.
When would I want to use an inner class over a decoupled way of doing it?
My only guess is when objects don't need to interact? (Or laziness??)
(Student)
This is actually called an anonymous inner class. You would use it if you only need to use the class once.
It would also reduce the size of your code unless it overrides many features of course (personally I prefer anonymous classes to be small in size for readability).
This Kind of Anonymous Inner Classes are called argument-defined inner classes,and automatically instantiated as part of the method invocation.
Here in the method argument, we get an object of a class,which is the subclass of the ActionListener Interface,but the newly created class is without any name(anonymous) so we cannot create its object again after the control passes through this statement.
now in the anonymous inner class which implements ActionPerformed Interface ,we override the actionPerformed() method which is very specific to that button and then new keyword creates an object of this anonymous class and it will automatically passed as argument.
or you may also create a new class(say myListener) which extends ActionListener class and overrides its actionPerformed() method. and then create a new object of myListener and pass it to the addActionListener()method as argument.
if you use metohod 2. you can see if you have 10 buttons and each have to perform different task ,then you have to create 10 ActionPerformed implementor classes and
pass object to the addActionListener() method of these implementor classes.
It is totally foolish to use this approach to create a whole new class just for a single object.
That's why most Listener are passed as an object of anonymous inner classes.
First of all this is not a question about how to implement an interface in Java, or about an error with interfaces. This is a question about the right way to do it, depending on the situation.
First of all i would like to apologize if this is not the correct "stack" to post this question, please let me know and i'll move it to another one.
Let's begin.
What i'm trying to guess is which is the best way to implement an interface in Java. Let's say we have a class A like:
public Class A {
public A(){}
public void fooA() {}
}
And an interface
public interface MyListener {
public void fooListener();
}
Inside fooA() I'm making use of interface B this way:
...
something.setFooListener(/**Doubts here**/)
....
What should we type inside setFooListener(...)
Options are (As far as i know):
A) Define the behavior inside the setFooListener function:
new MyListener.fooListener() {
/** Implementation of fooListener() **/
}
Pros:
Easy and readable as you're reading the function.
You can access directly to FINAL variables defined in fooA().
Cons:
If your implementation is long enough it would end up in a lack of readability and a too long function.
If you're implementing the interface in a few places on the same class you are going to repeat a lot of code.
B) Create an inner class implementing the interface:
private class MyListenerImplementation implements MyListener {
private String var1;
private int var2;
public MyListenerImplementation() {/** constructor **/}
public void fooListener() {
/** Do logic here **/
}
}
Pros:
You can keep a reference to the object MyListenerImplementation.
You can define variables, functions and everything as it's an object like any other one.
Cleaner code.
Cons:
Maybe needs more memory.
Maybe creating unnecessary classes
C) Hold a variable with a reference to the interface implementation
private MyListener.FooListener myListenerVar = new MyListener.FooListener() {
/** Logic goes here **/
};
Pros:
I actually can't sees anyone comparing to B, but a lot of cons.
Cons:
Not a clean code. Doing this on top of your class would be, at least, a war crime.
I don't think it's correct to assign a block of code to a variable.
I don't like how this looks ;)
D) The last one i could think of; define a function and inside return the implementation
private MyListener.fooListener createMyListener() {
return new MyListener.fooListener() {
/** Logic goes here **/
}
}
Pros:
It's cleaner than C.
Reusability
Cons:
Almost the same ones as C.
I don't think it's correct to return a whole block of code.
To sum up: Which i like the most is "B", but i would like to know what does SO thinks of this.
Thanks in advice.
Option A is not syntaxically correct. Your pros and cons are valid.
Option B:
Maybe needs more memory: no.
Maybe creating unnecessary classes: no. Option A also creates a class. It's anonymous, but it's a class, that must be loaded by the ClassLoader like any other class.
Option C: it's exactly the same as A (anonymous class usage), except you initialize a field with the listener. The rule is the same as for any other variable: reduce its scope as much as possible. If you need a field scope, use this option. If you only need the listener in one method, then use a local variable (option A).
Option D: once again, it's the same as A, except you return the created listener instead of only using it.
My recap: you're mixing three orthogonal problems here.
Should I use an anonymous inner class, a named nested class, or a top-level class. This depends on the amount of code contained in the class, and on where you need to use this class: in a single top-level class, or in many top-level classes.
Should I use local variables or instance variables. it's a matter of scope and state, not a matter of interface implementations. Your field or local variable can be initialized with an instance of any kind of your interface implementation
Should you use a factory method returning instances, or should you use new directly. Once again, that has nothing to do with how your interface is implemented. If you want to be loosely coupled, because the factory method might return different implementations of the same interface, use a factory. Otherwise, new is fine.
I am trying to teach myself Java and had a question that I wasn't able to answer so far. In some of my reading online I have found two ways of using action listener that seem to do the same thing. But I am trying to figure out what is the advantage/disadvantage of one over the other.
Is it better to use anonymous class like this:
public MyClass() {
...
myButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
//doSomething
}
});
...
}
or is it best to implement at the beginning of the class like so:
public MyClass() implements ActionListener {
...
myButton.addActionListener(this);
public void actionPerformed(ActionEvent e) {
//doSomething
}
...
}
Only if your class really is an ActionListener (is-a relationship) and will be used as an ActionListener somewhere else, it should implement ActionListener.
If it is just used internally as an ActionListener, implementing ActionListener would leak implementation details to the API of the class. Use composition in that case (has-a relationship).
This is true for other interfaces and superclasses as well.
This comes down to a style thing really. Both will perform exactly the same way in code.
The separate class will tend to keep the code inside your actual method simpler, whereas the anonymous inner class brings the code for the listener implementation within the method which can make it clearer what it is doing.
There is also the case that anonymous inner classes can access final variables in the method that creates them. You can't do that with a pre-written class (although you can pass the variables into the controller).
The separate code is re-usable - so if you have the same listener in multiple places then it is the clear winner.
If you use an anonymous class, the code becomes more readable, but you may not re-utilize it.
So, I would only use an anonymous class if it's short and I'm absolutely sure that I'll not have to use it again anywhere.
So I've stumbled across several ways of implementing an ActionListener and I'm wondering if someone can walk me through the differences of how each works and whether there are reasons or advantages to use one over the other?
The first is below in a block of code:
public void actionPerformed(ActionEvent arg0) {
// CODE HERE
}
The second way I saw was within another block of code as:
private class myListener implements ActionListener {
// CODE HERE
}
The third was is simply having a separate class for the ActionListener, with similar code to that above, but within a separate class.
I'm wondering whether the method approach is more efficient as new objects don't have to be created for each, you simply reference this as the ActionListener rather than, for example, referencing new myListener(). Thank you.
There's no difference in speed in any of the options; you'll always have an object that implements the ActionListener interface. Avoiding an instance of a separate class will just save you a few bytes of memory.
Your choice really should be based on what makes sense for your code, structurally. For example, having your public class implement ActionListener may look weird for those who are using that class, especially if the ActionListener behavior is supposed to be private to the class and not used outside it.
So it's mostly a choice of what you think looks better in your code; the only real difference will be with regards to field / method access (e.g. a separate, non-inner class won't have access to private methods and fields of your class, an anonymous inner class can't access non-final variables of the enclosing method, etc).
I don't like or use "implements ActionListener".
I do like and use anonymous inner classes like:
btnPurplescreen.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Color baseColor = Color.BLUE;
panelImage.setBackground(baseColor);
panelReference.setBackground(baseColor);
panelReference2.setBackground(baseColor);
baseType = BaseType.PURPLE;
}
});
You're stumbling in more ways that one.
In some sense, there is only one way to create a listener: there must be an object of a class that implements ActionListener, which means the class has the actionPerformed method.
There are three ways to do this:
You can modify a class you are already using for something else by marking it as implementing ActionListener and adding the actionPerformed method. This saves you creating a new class -- a savings of negligible value in most cases -- but mars otherwise perfectly good code. A few cases, when the existing
You can create a new named class. This is useful if you think the name is going to be meaningful to someone. If you are really using names like "MyListener", that's a clue that no, no-one cares about the name.
Finally, and usually, you can create an unnamed class. If all you want to do is add a fragment of code as a listener.
Whatever your choice, it's extremely unlikely to have any detectably effect on the time or memory performance of your finished system. The choice should be dictated by concerns about readability and maintainability.
I am looking at a codebase and I often see something like:
public class SomeClass
{
protected static SomeClass myObject;
//...
public static SomeClass getObject()
{
return myOjbect
}
}
I'd like to make sure I understand the purpose behind this. Is it to ensure one instance of the class gets shared even if it is instantiated multiple times? I am not sure about the vocabulary here, or else I'd search for the answer, so if this pattern has a name, please let me know.
Also, this seems a little chicken-and-egg definition because the class includes an object of the type of the class. Why isn't this actually paradoxical?
Thanks!
This is really only common with the Singleton Pattern where there is only this one instance of the class. While it has its uses, Singleton is over- and misused more often than not (usually to disguise procedural programming as OO). It also occurs very often in example code for Java AWT or Swing, where you typically subclass Frame / JFrame, and create an instance in a main method inside the same class.
Also, this seems a little
chicken-and-egg definition because the
class includes an object of the type
of the class. Why isn't this actually
paradoxical?
Why do you think it is? The class mainly describes what members instances of this type have - but a static member does not belong to an instance, it belongs to the class itself, so it doesn't have anything to do with the "blueprint" role of the class. Static members are really somewhat un-OO because of that.
But even on the instance level you can have references of the same type. For example, an entry in a linked list would typically have two references to the next and previous entries, which are of the same class.
This is called the Singleton design pattern.
You are correct in stating that the purpose is to ensure only one instance of the class gets created.
Wikipedia has a preyty good article on the pattern.
The pattern you mentioned is called "Singleton", but from your code sample it is not clear if this is really what is intended. Due to the fact that the member is protected, I would guess not - if there are subclasses, then there would probably not be a single instance.
It's called Singleton. You ensure the creation of just ONE (1) object of a given class.
You should add a private Constructor, so the only one who create the object is the class.
public class SomeClass
{
// Using private constructor
protected static SomeClass myObject = new SomeClass();
private SomeClass(){
//...
}
public static SomeClass getObject()
{
return myOjbect
}
}
Much much more here, in Wikipedia
You may want to take a look to Factory Pattern
It's not all that uncommon; it can be a good way to implement the Singleton pattern. There can be other uses as well - sometimes you will want a handful - and no more - of objects of a given class; that class is a good place to hang onto them. In the event that you don't want other classes to be able to create objects of this class, it is common to give the class a private constructor as well.
It's not paradoxical, because the compiler can be aware of a reference to the class before it has fully compiled the class. Later - if you like to think of it this way - it can "fill in the blanks".