- It seems that Runtime creates an "anonymous class" and implements the interface in it. Is that it?
Almost. Actually, whoever creates it is the compiler. If you do this within a Xpto
class, you may see a Xpto$1.class
file appear in the compiled class set. These classes generated by the compiler with $número
in the name are anonymous classes.
- What is the name of this situation?
Anonymous class.
- If this code was within a loop, would a new instance be created for each iteration?
The number of instances created is exactly the same as the number of times that the new
keyword is found. For example:
for (int i = 0; i < 10; i++) {
Collections.sort(obj, new Comparator<T>() {
@Override
public int compare(T t1, T t2) {
return 0;
}
});
}
Imagine that we replace the anonymous class with an implementation called Temp
:
class Temp implements Comparator<T> {
@Override
public int compare(T t1, T t2) {
return 0;
}
}
for (int i = 0; i < 10; i++) {
Collections.sort(obj, new Temp());
}
And then, it's clear where the instances are created.
- Would these instances all have the same type?
Yes, because the anonymous class is resolved at compile time. It is as if the compiler takes the whole body of the anonymous class, creates a new class file, copies and pasts that code there, and replaces the instantiation of the anonymous class with an instantiation of this class. Exactly as I did in the above code.
The purpose of anonymous class is to avoid the need to declare a complete class, the purpose being to simply provide a simple implementation of some interface or abstract class to do some silly work.
Another thing to note is the Java 8+ lambdas. For example, this:
Collections.sort(obj, new Comparator<T>() {
@Override
public int compare(T t1, T t2) {
return 0;
}
});
It's equivalent to this:
Collections.sort(obj, (t1, t2) -> 0);
Here, the compiler makes very aggressive and complex deductions so that the content of Comparator
has an extremely thin syntax.