Is it even possible?
Anonymous Function is a function that does not have any name associated with it. Normally we use the function keyword before the function name to define a function in JavaScript, however, in anonymous functions in JavaScript, we use only the function keyword without the function name.
It is an inner class without a name and for which only a single object is created. An anonymous inner class can be useful when making an instance of an object with certain “extras” such as overriding methods of a class or interface, without having to actually subclass a class.
Anonymous functions: a function that isn't bound to a name/variable. In Java it means a function that doesn't belong to a class, but rather one that's implemented as defined by an implementation in a functional interface.
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.
if you mean an anonymous function, and are using a version of Java before Java 8, then in a word, no. (Read about lambda expressions if you use Java 8+)
However, you can implement an interface with a function like so :
Comparator<String> c = new Comparator<String>() { int compare(String s, String s2) { ... } };
and you can use this with inner classes to get an almost-anonymous function :)
Here's an example of an anonymous inner class.
System.out.println(new Object() { @Override public String toString() { return "Hello world!"; } }); // prints "Hello world!"
This is not very useful as it is, but it shows how to create an instance of an anonymous inner class that extends Object
and @Override
its toString()
method.
Anonymous inner classes are very handy when you need to implement an interface
which may not be highly reusable (and therefore not worth refactoring to its own named class). An instructive example is using a custom java.util.Comparator<T>
for sorting.
Here's an example of how you can sort a String[]
based on String.length()
.
import java.util.*; //... String[] arr = { "xxx", "cd", "ab", "z" }; Arrays.sort(arr, new Comparator<String>() { @Override public int compare(String s1, String s2) { return s1.length() - s2.length(); } }); System.out.println(Arrays.toString(arr)); // prints "[z, cd, ab, xxx]"
Note the comparison-by-subtraction trick used here. It should be said that this technique is broken in general: it's only applicable when you can guarantee that it will not overflow (such is the case with String
lengths).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With