hello developer community, I want to implement the same method in two anonymous classes to save myself from writing this method several times, the algorithm is a bit more complex but I want to give an example with this:
public class MainActivity extends AppCompatActivity {
interface $miinterfaz{
void primero(Integer entero);
void segundo();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
$miinterfaz inter1=new $miinterfaz(){//primera clase anónima
@Override
public void primero(Integer entero) {
int nuevoentero=entero+10;//aca solo le sumo 10
Log.i("este metodo cambia","entero = "+nuevoentero);
}
@Override
public void segundo() {
Log.i("este metodo es el mismo","solo quiero imprimir este mensaje");//este mensaje es igual en los dos casos
}
};
$miinterfaz inter2=new $miinterfaz(){//segunda clase anónima
@Override
public void primero(Integer entero) {
int nuevoentero=entero+50;//aquí es diferente el calculo sumándole 50
Log.i("este metodo cambia","entero = "+nuevoentero);
}
@Override
public void segundo() {
Log.i("este metodo es el mismo","solo quiero imprimir este mensaje");
}
};
ejecutar(inter1);
ejecutar(inter2);
}
public void ejecutar($miinterfaz inter){
inter.primero(8);
inter.segundo();
}
}
so the question is how do I copy the second method in the other anonymous class? or if there is another technique to avoid writing this method several times but taking into account that the first one does change, so the log remains:
I/este metodo cambia: entero = 18
I/este metodo es el mismo: solo quiero imprimir este mensaje
I/este metodo cambia: entero = 58
I/este metodo es el mismo: solo quiero imprimir este mensaje
Since interfaces are just method signatures, what you require is a method implementation. What I would do would be a class that implements an interface with the required method and there I would write the implementation of the method. That way I would avoid overriding the interface method every time I use it.
I hope I made myself understood.
What creates the need to do two instances is only the value of the increment. If the increment is passed as a parameter to the function
primero()
, two different instances are not needed.Create a single instance
using an internal class and implementing the interface I could override the function that is not dynamic and change it to yes in each instance
this is the log