Is it even possible?
if you mean an anonymous function then in a word, no.
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.
See also
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).
See also
- Java Integer: what is faster comparison or subtraction?
- Comparison-by-subtraction is broken in general
- Create a Sorted Hash in Java with a Custom Comparator
- How are Anonymous (inner) classes used in Java?
Anonymous inner classes implementing or extending the interface of an existing type has been done in other answers, although it is worth noting that multiple methods can be implemented (often with JavaBean-style events, for instance).
A little recognised feature is that although anonymous inner classes don't have a name, they do have a type. New methods can be added to the interface. These methods can only be invoked in limited cases. Chiefly directly on the new
expression itself and within the class (including instance initialisers). It might confuse beginners, but it can be "interesting" for recursion.
private static String pretty(Node node) {
return "Node: " + new Object() {
String print(Node cur) {
return cur.isTerminal() ?
cur.name() :
("("+print(cur.left())+":"+print(cur.right())+")");
}
}.print(node);
}
(I originally wrote this using node
rather than cur
in the print
method. Say NO to capturing "implicitly final
" locals?)
i seee... so at java we didnt say it as inner function instead... inner object or interface tech... :D
whuaaah! Now I got a bit clear picture from both php n java perspective... :D