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.
Related
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. :)
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.
just a quick question....
I am working in Java. I have 2 separate classes:
public class MulticastChatGUI extends javax.swing.JFrame{
}
and
public class MulticastThread extends Thread{
}
So, all I am really trying to do is to access an element from the GUI from within the Thread class, namely a Text Area. Is this possible? Thanks in advance for what is probably a very simple question.
Is it possible? Yes, but it must be done with care.
For instance you could give your MulticastThread class a MulticastChatGUI variable, and then pass in a reference of the current MulticastChatGUI instance into the MulticastThread object via a constructor parameter or a setter method.
e.g.,
// constructor
public MulticastThread(MulticastChatGUI multicastChatGui) {
this.multicastChatGui = multicastChatGui;
}
// or setter
public void setMulticastChatGUI(MulticastChatGUI multicastChatGui) {
this.multicastChatGui = multicastChatGui;
}
Up to now, the problem and solution is the same for any program where you want one class to talk to another.
Care must be taken however that whenever you call a Swing method on the JTextArea, you do so only on the Swing event thread, else you risk occurrence of a pernicious, hard to debug, and intermittent threading exception.
Note that it is cleaner not to have one object access the other object's fields directly (here the JTextArea), but instead have the class with the JTextArea make it private, and give it public methods that allow outside classes to change its shape in a controlled manner.
I want to call a validation method inside a shared gwt class that i have created to store the validation logic (for user entered text fields)
suggestBox.addKeyUpHandler( new KeyUpHandler() {
public void onKeyUp(KeyUpEvent event) {
if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
String boxText = suggestBox.getText();
if (new FieldVerifier().validUserName(boxText)) { //inner class used to instanciate the FieldVerifier class where validUserName(String ..) lives
now i could do this with a properly instanciated FieldVerifier class (rather than a inner class as above) - or indeed, perhaps make it abstract. but i have the suspicion i am missing something (ie. must be an elegant way of doing it).
looked on google code search, but didnt come across anything particularly helpful..
I'm not sure I got it, but try:
FieldVerifier.this.validUserName(boxText);
If you made the validUserName() method of FieldVerifier static then you could just call FieldVerifier.validUerName() directly, without having to instantiate a FieldVerifier object. If it's a fairly small class, though, the overhead of creating a new object is likely to be minimal.
i could do this with a properly instanciated FieldVerifier class (rather than a inner class as above)
Your use of FieldVerifier is not an inner class. It is indeed 'properly instanciated'. KeyUpHandler is an example of an anonymous inned class.
If I understand what you're trying to do, I would make validUserName() a static method. It doesn't appear to require or change any state; you just pass in something, run some verification logic on it, then return a boolean. This case is when you want to start looking at using statics.