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.
Related
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.
By making private constructor, we can avoid instantiating class from anywhere outside. and by making class final, no other class can extend it. Why is it necessary for Util class to have private constructor and final class ?
This is not a mandate from a functional point of view or java complication or runtime. However, it's a coding standard accepted by the wider community. Even most static code review tools, like checkstyle, check that such classes have this convention followed.
Why this convention is followed is already explained in other answers and even OP covered that, but I'd like to explain it a little further.
Mostly utility classes are a collection of methods/functions which are independent of an object instance. Those are kind of like aggregate functions as they depend only on parameters for return values and are not associated with class variables of the utility class. So, these functions/methods are mostly kept static. As a result, utility classes are, ideally, classes with only static methods. Therefore, any programmer calling these methods doesn't need to instantiate the class. However, some robo-coders (maybe with less experience or interest) will tend to create the object as they believe they need to before calling its method. To avoid that, we have 3 options:
Keep educating people to not instantiate it. (No sane person can keep doing it.)
Mark the utility class as abstract: Now robo-coders will not create the object. However, reviewers and the wider java community will argue that marking the class as abstract means you want someone to extend it. So, this is also not a good option.
Private constructor: Not protected because it'll allow a child class to instantiate the object.
Now, if someone wants to add a new method for some functionality to the utility class, they don't need to extend it: they can add a new method as each method is independent and has no chance of breaking other functionalities. So, no need to override it. Also, you are not going to instantiate it, so no need to subclass it. Better to mark it final.
In summary, instantiating a utility class (new MyUtilityClass()) does not make sense. Hence the constructors should be private. And you never want to override or extend it, so mark it final.
It's not necessary, but it is convenient. A utility class is just a namespace holder of related functions and is not meant to be instantiated or subclassed. So preventing instantiation and extension sends a correct message to the user of the class.
There is an important distinction between the Java Language, and the Java Runtime.
When the java class is compiled to bytecode, there is no concept of access restriction, public, package, protected, private are equivalent. It is always possible via reflection or bytecode manipulation to invoke the private constructor, so the jvm cannot rely on that ability.
final on the other hand, is something that persists through to the bytecode, and the guarantees it provides can be used by javac to generate more efficient bytecode, and by the jvm to generate more efficient machine instructions.
Most of the optimisations this enabled are no longer relevant, as the jvm now applies the same optimisations to all classes that are monomorphic at runtime—and these were always the most important.
By default this kind of class normally is used to aggregate functions who do different this, in that case we didn't need to create a new object
Util class in java can be made in two ways
class Utils
{
public static ReturnType someUtilMethod(
// ...
}
and execute util method by
Utils.someUtilMethod(...);
Or I can make
class Utils
{
public Utils(){}
public ReturnType someUtilMethod(
// ...
}
and execute util method by
new Utils().someUtilMethod(...)
What way is better? Are some differences between this ways?
Generally Util class contains Utility methods which doesn't need to store the state of Object to process and so static methods are good fit there
A utility function should always be static, unless for some reason it depends on the state of some other variables, and those variables need to be remembered between calls.
The latter should almost never happen, although something like a pseudo-random number generator might be a good case.
The Math functions are a good example of utility functions. When you call Math.sin() the result depends only on the supplied parameter. There is no "state" involved, so there's no need to create an object.
static access will be a better approach as in Util class hold methods which are not concerned with the attributes of the Objects.
Another example will be of Math Class.
Math class has no Instance variables.
And has private constructor, so no object can be created.
So in Math class case using static access like Math.PI is appropriate.
If you use a class that only has static methods, you will not need to instantiate the object everytime you need to use it, saving a line of code and some memory. Just remember to make the default constructor private, so that no one cane inadvertently instantiate it!
A utility class is just a place where to syntactically hold global functions in Java.
Your second example is not covered by the term "utility class". The definition of that concept includes non-instantiability of the class.
The reason to have instance methods would be dynamic method dispatch (to achieve polymorphism), or possibly hold some non-global state. But, as I said, then you would be out of the scope of the term "utility class".
I have been facing so many problem using the anonymous class like I can't perform the instanceOf test neither can I implements multiple interface, so could someone please explain what I can or can not do with the anonymous class in java ?
The purpose of an anonymous inner class is to extend and instantiate an existing class or implement a single interface in one step.
Its limitations can be derived from the above:
Only one non-final class can be extended or one interface implemented.
Only final local variables of the enclosing method can be accessed. (This is due to the fact that normal local variables will be out of scope by the time any methods of the inner class will be invoked.)
You can't define a constructor. (The class has no name.)
If you need multiple interfaces, you can use a local inner class, which is like a normal inner class, with its own name, but defined within a method. I have to admit I've never seen it used in practice and I see very little reason for anyone to do so, hopefully someone will come up with an example.
Anonymous classes work whenever
you never need to refer to the class itself
you only need to extend a single class or implement a single interface
...but other than that there aren't really any significant constraints. This works fine in a lot of cases: for example, many cases when you're defining callbacks, listeners, or the like.
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);.