When you overwrite a method, whether in an anonymous class or not, you must respect the signature of the method you are overwriting. This is the basis on which works on polymorphism , which is one of the main features of the POO.
The signature is the quantity, type and order of the parameters that the method receives. For simplicity and to explain the concept, I will give an example with declared classes, do not forget that it is the same with anonymous classes.
Suppose we have a class, declared this way.
class Lenguaje
{
public void saludarA(String nombre)
{
System.out.println("funcionalidad de saludo no definida " + nombre);
}
}
This should be an abstract class, but here I leave it with the method implemented if the reader is not so advanced in java. The advanced programmer, please excuse my audacity.
The idea is to declare several classes that inherit from Lenguaje
, for example Espaniol
e Ingles
, but at a certain moment, have a method that acts polymorphically on them, for example an iteration on a collection of Languages , something like:
Collection<Lenguaje> lenguajes = new ArrayList<Lenguaje>();
collection.add(new Espaniol());
collection.add(new Ingles());
collection.add(new Aleman());
Iterator<Lenguaje> iterator = lenguajes.iterator();
while (iterator.hasNext()) {
iterator.next().saludarA("Juan");
}
This would eventually print to console something like:
Hola Juan
Hello Juan
Hallo Juan
It is for this reason that java, and in general, the OOP languages, demand that the descendant classes, when overwriting the methods, respect the signature. In this way, the logic behind calling the method and passing the list of parameters is the same, regardless of whether height of the hierarchy is the class that implements the method . Until now I do not know a compiled language that solves this in another way, to allow that eventually other parameters can be passed that the ancestor class does not know.
For the curious, a possible descendant class would be like this:
class Espaniol extends Idioma
{
@Override
public void saludarA(String nombre)
{
System.out.println("Hola " + nombre);
}
}
Warning: The code may not compile, it is set as an example, I have written it directly in the browser. The idea is to give an example for reading a human , not a compiler.
In the long run, your anonymous class is not very different from this class. It is a type of syntactic sugar , to save you having to write the declaration of a complete class. But from behind, it's a class like any other. If you think about it a bit, in this case, it is based on the polymorphism, as I have shown in the example, so that the code that anyone on the planet can write when an action occurs in an application.