Most of the research I have done keeps coming up with the same thing which is java implements callbacks using anonymous classes before java 1.8 or lambda expressions in java 1.8 and above.
It has been stated on the “Is a function callback in Java also an anonymous class?” question that callbacks() can be implemented 2 ways in java which makes sense to me. ( correct me if I am wrong )
From code example #1. below, YourMouseListener is defined so all we have to do is instantiate an object and pass that instance to a method, meaning callbacks() can be implemented without anonymous classes or lambda expressions.
In code example #2 solution is implemented with anonymous class which is fine, I just don’t see that it brings any functionality that can’t be done with example #1 methodology.
So, actually, the first way to implement this callback is you declare a class extends MouseAdapter
public class YourMouseListener extends MouseAdapter() {
public void mouseEntered(MouseEvent e) { ... }
}
// then create an instance and passes to it:
c.addMouseListener(new YourMouseListener() );
To minimize code and class declaration, Java enable you to use anonymous classes to achieve callbacks() like:
c.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent e) {
System.out.println("Mouse entry event: " + e
+ " on button: " + buttonLabel); }});
So my question is, in Java, can callbacks be implemented without anonymous classes and lambda expressions?
Thanks in advance.
Yes, of course! Callbacks, event listeners, etc. are just types. Java gives many ways to create implementations of interfaces, including anonymous classes and lambda expressions (for functional interfaces).
The option of providing implementations using normal classes is always open. Sometimes it's even preferred, as in cases where the code would be duplicated when the same kind of callback is passed for different events.
The drive for anonymous classes and lambda expressions is brevity and, of course, the fact that callbacks are usually fit-for-purpose code that you use for one event (such as a specific listener code for specific buttons - it's only in rare cases that one needs to reuse code for things like mouse click events).
In many cases, it's convenient to write just the code for it using a lambda expression (when a functional interface applicable) or an anonymous class, instead of writing a separate class for it.
Anything you can do with an anonymous class you can do with a named class. Just declare a named class that does the same thing. Anonymous classes were just a convenience to avoid having a bunch of class definitions that were used only once.
A callback would be expressed as an interface passed as an argument to a method. Whether the object implementing the callback is instantiated using a named class or an anonymous class makes no difference to the JVM.
Related
This question already has answers here:
What are functional interfaces used for in Java 8?
(11 answers)
Closed 3 years ago.
Recently I started in a new project where all the interfaces with a single abstract method are anotated with #FunctionalInterface. Constantly I see people removing the annotation after adding another abstract method in the interface. When did I ask why? They told me that someone that isn't in the company anymore told them to do it like that. Now I'm not sure if it's a good idea to annotate interfaces that obviously will not be used with lambdas.
Now I see that a piece of useful information is that people are using the anotation even in services in services. I just seemed a code like:
#FunctionalInterface
public interface SomeService {
void doSomething();
}
I'm not sure if it's a good idea to annotate interfaces that obviously
will not be used with lambdas
It's not. At best, it's a waste of time. At worst, it's actively misleading.
The documentation says
[Use to indicate that the type] is intended to be a functional interface
If you say it will "obviously not" be used in a lambda then using a annotation that marks that you do expect that usage is a clear contradiction.
Explanation
Every interface that only offers one (abstract) method, i.e. without implementation, is a so called functional interface.
Being it explicitly or implicitly.
The annotation #FunctionalInterface is, like #Override, optional, if you want to create a functional interface.
So if you declare an interface #FunctionalInterface, but it actually has more than just one such method, the compiler helps you and prevents compilation with an error. Telling you that you violated your own intention.
If you do not have the annotation, it will compile, but it is not a functional interface anymore. This could be a bug to you, because your intention was to create a functional interface. Note that if you are actually using the interface in an environment where a functional interface is actually required, like for a lambda, it would obviously not compile anymore as soon as another method is added to the interface.
Here are some examples:
// is a functional interface
interface Foo {
void bar();
}
// is a functional interface
#FunctionalInterface
interface Foo {
void bar();
}
// is not a functional interface
interface Foo {
void bar();
void baz();
}
// does not compile
#FunctionalInterface
interface Foo {
void bar();
void baz();
}
Use
It is to make your intention clear to the compiler, other team members and your future self. That way, the compiler can help you spot bugs in case you mess up.
Another scenario might be if you are working in a team and design an interface. If you do not clearly mark this interface as functional interface, either by the annotation or with a comment/documentation, another team member might not know your intention and add more methods to it.
This is especially important if you are a library designer, i.e. writing code that is to be used by other, external, people. If you mark your interface #FunctionalInterface, it is a promise to them that you intent to keep it like that. So they can safely use it for lambdas, for example. Without fearing that their code will break as soon as you ship an update to your library.
The opposite case is true as well. If they spot an interface of yours that only has one method, but is not explicitly annotated, they will understand that this is not meant to be used as functional interface, eventhough it currently is one. Thus, they will not use it for lambdas, although they could, since you might change it in a future update.
Details
You can read about the precise definitions in JLS§9.8. Functional Interfaces:
A functional interface is an interface that has just one abstract method (aside from the methods of Object), and thus represents a single function contract. This "single" method may take the form of multiple abstract methods with override-equivalent signatures inherited from superinterfaces; in this case, the inherited methods logically represent a single method.
And JLS§9.6.4.9. #FunctionalInterface:
The annotation type FunctionalInterface is used to indicate that an interface is meant to be a functional interface (§9.8). It facilitates early detection of inappropriate method declarations appearing in or inherited by an interface that is meant to be functional.
It is a compile-time error if an interface declaration is annotated with #FunctionalInterface but is not, in fact, a functional interface.
Because some interfaces are functional incidentally, it is not necessary or desirable that all declarations of functional interfaces be annotated with #FunctionalInterface.
The last paragraph here is especially important. I.e. you might have created a functional interface incidentally and plan to add more to it later. So people should not mistake this and use it with lambdas, otherwise their code will break later, when you add more methods.
Note
As mentioned before, the #Override tag works the same, but for overriding methods. So you can also override methods without it. But if you use it and maybe made a typo, i.e. you are not actually overriding something, the compiler will help you spot this issue immediately.
This is from an article from oracle about anonymous classes I was reading:
Anonymous classes are ideal if you have to implement an interface
that contains two or more methods
I though that is ideal if you have to implement fewer than two methods, cause you don't need to make more concrete named classes, but if you have to implement more than two will be more unreadable.
My question is:
Why should implementing anonymous classes with 2 or more methods be ideal?
You took that sentence out of context. Look at the sentence immediately before that one:
Because the EventHandler<ActionEvent> interface contains only one
method, you can use a lambda expression instead of an anonymous class
expression. See the section Lambda Expressions for more information.
(emphasis by me)
You'll be able to use lambda expression instead of anonymous classes with only a single method in the future, so using an anonymous class only makes sense if your interface has more than one method.
Readability might suffer if it has many methods, but there is no other language construct that enforces that a specific implementation may only be used at one point in the code.
The article is including information from JDK 8, in which case Lambda expressions can be used to implement single function interfaces instead of having to use an anonymous class.
So the 2+ method suggestion is strictly for JDK 8, for 7 and below anonymous classes are the only way (well, outside of full classes) for single method and multiple method interface implementations.
This is probably taking into account the new concise syntax available in Java 8 (fingers crossed) for single-method interfaces (i.e. Lambda Expressions). That would provide a better option than anonymous classes if the interface does indeed only have a single method.
How is it helpful to use anonymous class if every time we have to define a class while invoking a constructor of an interface.Wouldn't it be more better to simple use a generic type instead?
Anonymous classes is frequently used in GUI applications. When you only need to declare and create object of a class at the same time, it can make the code more precise.
Here is an example:
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
System.out.println("Hello World!");
}
});
Anonymous classes are not defined every time they are instantiated. They get compiled into bytecode just like other classes, with a name e.g. MyEnclosingClass$1. See this post for more information: How are anonymous classes compiled in Java?
Tangentially, reflection can be used to identify them at runtime using Class.isAnonymousClass().
It depends on the situation; in some cases it will be better to use an anonymous class, and in others, it will be better to use a concrete class that implements the required interface.
If you believe that you'll need to provide the same anonymous class definition repeatedly, it will likely save you time to pass an instance of a concrete class that implements the required interface.
The Java language provides anonymous class syntax as a convenience.
To give you just a taste, here's a quick example from my own experience: Having lists backed by functions.
In general, anonymous classes have (among others) the following uses:
Suppose you want to have an object (an instance, not a class) whose behavior depends on some value available at runtime. Without anonymous classes, you can do this by setting fields (or calling state-changing methods) - but you can't have different code executing. Now, true, you could have bunch of switch() statements in your class' method code - but that completely decouples the definition of the behavior from its context. Another way you could go is to use a named subclass, but that's a lot of code, and it creates a noun you don't really want to exist.
Functional Programming! Until Java 8 comes along, anonymous functions are just about the only way you can pass around functions, which are not first-class citizens in Java. With those, you can perform many neat and elegant tricks like my example above.
Take the following example. There's an object I want to use, call it a Doodad. Doodad elements have poorly implemented handling of browser events. Typical instantiation of a Doodad would be Doodad someDoodad = new Doodad();. Obviously this isn't suiting my needs because of the poor event handling. Is it appropriate for me to override the onBrowserEvent() method, like so:
Doodad someDoodad = new Doodad() {
#Override
public void onBrowserEvent(Event event) {
switch (DOM.eventGetType(event)) {
case Event.ONDBLCLICK:
case Event.ONFOCUS:
case Event.ONCLICK:
if (!isEnabled()) {
return;
}
break;
}
super.onBrowserEvent(event);
}
};
Obviously this is a simple example, but when might I not want to use an anonymous inner class? Is it ever explicitly disallowed or impossible?
I'm seeing lots of answers to the first question, but none of the answers so far answer the second: Is it ever explicitly disallowed or impossible to use an anonymous inner class?
Typically the best usage of anonymous inner classes is when you want to create only one instance of specific implementation of this class. And when the implementation is pretty simple. Ideally it should contain 1-2 lines of code.
In your case it is still OK although your method onBrowserEvent() is longer than 2 lines.
Anonymous inner classes is Java's syntax for creating closures. Here's an approximate example:
interface Adder {
int add(int arg);
}
...
Adder createAdder(int n) {
final int nf = n;
return new Adder() {
int add(int arg) { return arg + nf; }
}
}
Method createAdder creates what essentially is a function using a closure to capture the passed value n. Closures are important in functional programming which is trying to make it into mainstream. This is why everyone is screaming that we need "real" closures in Java (i.e. mostly better syntax than in my example).
(Of course I'm not answering the question asked; I think what I'm saying is that anonymous classes are good for what I described above. for almost everything else I would create a named inner class because if anything name is self-documenting and is in my opinion easier to read)
Often, an event listener is a piece of code that is not very generic, but is tied to a specific widget, a button, a text-field, whatever. In such a case, the code does not need to be properly exposed for the world to reuse it. It is easier to define it where it is used, in place, and that's what anonymous inner classes are for. They allow to quickly embed pieces of code inside another method, without having to worry about class names, packages, visibility, or re-usability.
Of course, what you can do with anonymous inner classes can always be done with proper stand-alone classes. But it makes more sense to do it this way when your event handling class is generic enough (can handle lots of events), is reusable, is stateful, or more generally when there is some benefit from extracting the event management code from the code that defines the event-generating element.
I'm not sure I understand specifically your question, I hope this piece of info will help you find your answer. Do not hesitate to ask further questions.
I would suggest anonymous classes when it implements one method and/or is half a screen full.
If the anonymous has non trival piece of code its worth having a named class IMHO.
My take:
Anonymous inner classes: Callback from one function (so you don't write the code twice)
Named inner classes: Callbacks from several functions (or a class that you need only for the internal logic of the parent class)
I only use an anonymous inner class when it contains a very small amount of code. Reason is IMO it clutters up the code and makes it less readable.
If there is more code required, I prefer to create a new class, extending the base class (in this case 'Doodad()'
In your example you would want to create a separate class. This is because of the reason why you are overriding the method. That is, there is poor handling for browser events.
Specifically, you may want to create these improved Doodads in a couple of different places. And what happens if the event handling is updated and improved in the future? You'll want to remove all of these improved Doodads and use the proper implementation. Trying to find all your anonymous Doodads may be tiresome or tricky. Whereas if you have a separate named class then refactoring out this class will be easy.
In addition the reason for your improving the Doodad can be self documenting if you create a separate class for it. Whereas if you just have an anonymous class then you will have to write comments or leave future maintainers guessing why you've done what you've done.
eg.
public class ImprovedBrowserEventHandlingDoodad extends Doodad {
...
}
Anything that resembles a closure is normally a good candidate for using an anonymous class
eg.
new Thread(new Runnable() {
#Override
public void run() {
doSomething();
}
}).start();
You only want to do something in this one specific set of circumstances and there is no need to copy and paste the code somewhere else or to refactor it into a method.
Event handlers for GUIs are typical in using anonymous classes because their use is limited to the how the GUI is designed and there is no need to create a separate instance of the event handler outside the specific component that is using it. For instance, when you mouse over a scroll bar its appearance generally changes. Nothing else in the program will cause this change and typically the event handler will be a couple of lines telling the scrollbar to change its appearance eg. scrollbar.setMouseOverEffect(true);.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I know anonymous classes save typing when it comes to implementing Listener and similar stuff. They try to be a replacement for some usages of closures.
But what does the community think about the value of this language-feature? Does it make sense and do you use it regularly? Does it make the code clearer, more understandable and more maintainable? Or do anonymous classes make the code less readable?
What is your opinion, and please have examples/arguments handy to support your opinion?
I tend to use anonymous inner classes in situations where I don't need to have a full-blown class just to perform some task. For example, if I want to implement an ActionListener or Runnable, but I don't think having an inner class would be necessary. For example, for starting a simple Thread, using an anonymous inner class might be more readable:
public void someMethod()
{
new Thread(new Runnable() {
public void run()
{
// do stuff
}
}).start();
}
In certain cases, such as the example above, it can increase readability, especially for one-time tasks, as the code that is to be executed is all written in one spot. Using an inner class would "delocalize" the code:
public void someMethod()
{
new Thread(new MyRunnable()).start();
}
// ... several methods down ... //
class MyRunnable implements Runnable
{
public void run()
{
// do stuff
}
}
That said, however, if there is going to be cases where the same thing is going to be repeated, it should indeed be a separate class, be it a regular class or an inner class.
I tend to use anonymous inner classes in programs where I am just trying things out rather than have it as a central feature of an actual application.
One more good use of anonymous inner class is when you need to initialize collections like ArrayList and Set. This practice is also known as double brace initialization
For example ,
private static final Set<String> VALID_CODES = new HashSet<String>() {{
add("XZ13s");
add("AB21/X");
add("YYLEX");
add("AR2D");
}};
Obviously, this is not limited to collections; it can be used to initialize any kind of object -- for example Gui objects:
add(new JPanel() {{
setLayout(...);
setBorder(...);
add(new JLabel(...));
add(new JSpinner(...));
}});
My opinion is anonymous classes makes the code less readable. For implementing listeners anonymous classes are useful. For developing a GWT application anonymous classes are the better choice.
For these cases, if we are not using anonymous classes then the number of lines of code will increase.
We use anonymous classes regurlarly. I find them easy to use for implementing interfaces that have only one or two methods and that where the functionality isn't used anywhere else. If you use the same functionality again somewhere else there should be a real class to be reused.
Whether using anonymous class improves or degrades legibility is a matter of taste. The main issue is definitely not here.
Anonymous classes, like inner classes, carries a reference to the enclosing class, thus making non private things that without it would be. To be short, the this reference of the enclosing class may escape through the inner class. So the answer is: it is a very bad practice to use an inner class if it published itself, since that would automatically publish the enclosing class. for example:
changeManager.register(new ChangeListener() {
public void onChange(...) {
...
}});
Here, the anonymous ChangeLstener is passed to the register method of a ChangeManager. Doing so will automatically publish the enclosing class as well.
This is definitely a bad practice.
I use anonymous classes mostly for interfaces that have only a single method, i.e. Runnable or ActionListener. Most larger interfaces warrent their own classes or implementation in an already existing class. And as it is my opinion I don’t need arguments to support it.
If limiting scope and access as much as possible is a good thing, then anonymous classes are very good. They are limited in scope to the one class that needs them. When that's appropriate, I'd say anonymous classes are good.
The instant you duplicate the same function, it becomes a bad idea. Refactor it into a public class that stands on its own. IDEs with refactoring features make that easy.
Anonymous class is mostly seen in GUI application specially for events handling.Anonymous class is useful in cases of implementing small interfaces that contains one or two methods..For example.. you have a class where you have two or three threads and you want to perform two or three different tasks using those threads.In this situation you can take the help of anonymous class to perform your desired tasks. look at the follow example
class AnonymousClass{
public static void main(String args[]){
Runnable run1=new Runnable(){
public void run(){
System.out.println("from run1");
}
};
Runnable run2=new Runnable(){
public void run(){
System.out.println("from run2");
}
};
Runnable run3=new Runnable(){
public void run(){
System.out.println("from run3");
}
};
Thread t1=new Thread(run1);
Thread t2=new Thread(run2);
Thread t3=new Thread(run3);
t1.run();t2.run();t3.run();
}
}
output:
from run1
from run2
from run3
In the above snap of code i have used three threads to perform three different tasks. Look i have created three anonymous classes that contains the implementation of the run method to perform three different small tasks.
It makes sense to use them, but you must be aware of whats being done underneath. I only use them if I need a class to do something very specific that I don't need anywhere else.
It depends what you compare them to. I'd rather have them than not have them, but then I'd rather be able to supply plain code blocks to methods like Arrays.sort() than having to explicitly create a class containing my implementation of compare().
I use Anonymous classes mostly
a) shorthand notation if the interface has one or two methods and it wont affect the readability
b) situation where I wont be able to justify creation of a new class, for example In swing when you have to attach an actionlistner to lets a JButton for some trivial operation.
I agree with what many others have said in that they are useful for small interfaces when only used once. But I would also add the restriction that if code external to the anonymous class has to be altered for it to work, then don't use an anonymous class.
If you have to start declaring variables as final to accommodate the anon class since it references them, then use an inner class instead. I have also seen some bad code smells where final arrays (of size 1) are used to return results from anon classes.
There is nothing inherently different or special about anonymous classes. They are ultimately just syntactical sugar with support for referencing the outer class. This makes it easier to author adapters - just like most of the Iterator implementations returned by the Collections framework.
Anonymous classes don't "Hide" code but they do TEND to make it slightly less reusable. Note that this applies to closures as well.
In some ways they allow some nice refactors because you are allowed to pass code into a method. This can be used very effectively to reduce duplication and I'm certainly not against Anonymous classes/closures, however there are a few cases where they can be a drawback.
First consider that the anonymous inner class code you are passing in does not lend itself to reuse in your code. If you are doing the same thing in some other code you'd have to re-write it as something other than an anonymous inner class in order to reuse it and at that point it could be difficult to even know that there is code elsewhere to reuse.
Along with the lack of reuse is it's difficulty to parameterize, which leads to my biggest complaint... they tend to lead to copy and paste code.
I've seen quite a few GUIs where someone started with anonymous inner classes as event responders. Many had to do something slightly different, For instance, 5 lines of code where the only difference is a string in the middle. Once you are in the habit of using inner classes the easy solution is to copy and paste the block and replace that string.
The solution of creating a new "Named" class that has a string parameter and passing that class to all the methods rarely occurs to someone at that point. This named class can use parameters or inheritance to define different behaviors as well as code.
I'm a fan of closures and don't hate anonymous classes--just pointing out some pitfalls I've seen.
So with java 8 new feature of static methods in interfaces, you can use an anonymous inner class to return an instance of your interface. For example:
interface Person {
String getName();
int getAge();
static Person newInstance() {
return new Person() {
public String getName() {
return "Bob";
}
public int getAge() {
return 99;
}
}
}
}
And you can get an instance like so:
Person person = Person.newInstance();
Basically this allows for a single default implementation of your interface.