- It seems that Runtime creates an "anonymous class" and implements the interface on it. That’s it?
Almost. Actually who creates it is the compiler. If you do this within a class Xpto
, you may see a file Xpto$1.class
appear in the compiled class set. These classes generated by the compiler with $número
in name are anonymous classes.
- What name is given to this situation?
Anonymous class.
- If this code was inside a repeat loop, a new instance would be created for each iteration?
The number of instances created is exactly the same as the number of times the keyword new
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;
}
});
}
Suppose 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 becomes clear where the instances are created.
- These instances would all have the same type?
Yes, because the anonymous class is solved at compile time. It is as if the compiler took the entire body of the anonymous class, created a new class file, copied and pasted that code there, and replaced the instantiation of the anonymous class with an instantiation of this class. Exactly as I did in the code above.
The purpose of the anonymous class is exactly to avoid the need to declare a complete class and the purpose is just to provide a simple implementation of some interface or abstract class to do some silly work.
Another thing to note are the Java 8+ files. For example, this:
Collections.sort(obj, new Comparator<T>() {
@Override
public int compare(T t1, T t2) {
return 0;
}
});
Is equivalent to that:
Collections.sort(obj, (t1, t2) -> 0);
Here, the compiler makes very aggressive and complex deductions so that the content of Comparator
has an extremely lean syntax.