Java -Funktion Überladen für Array von Objekten, die eine gemeinsame Schnittstelle implementieren [Duplikat]
Posted: 02 Apr 2025, 03:54
Ich habe Klassen, die eine gemeinsame Schnittstelle implementieren. In der Schnittstelle wird die Funktion mit 3 Parametern definiert. Für einige Klassen implementieren sie jedoch eine Schnittstelle, die die gemeinsame Schnittstelle erweitert, die die Funktion überlastet und 5 Parameter aufweist. < /P>
.
implementiert eine Schnittstelle, die die gemeinsame Schnittstelle implementiert, und da ich mein Array als vom Typ CommonInterface definiert habe, können wir die Methode anwenden mit 5 Parametern aufrufen?>
Code: Select all
public interface CommonInterface{
public double apply(Object param1, double param2, double param3);
}
public class CommonClass implements CommonInterface{
public double apply(Object param1, double param2, double param3){
doSomething();
}
}
< /code>
public interface DifferentInterface extends CommonInterface{
public double apply(Object param1, Object param2, Object param3, double param4, double param5);
}
public class DifferentClass implements DifferentInterface{
public double apply(Object param1, double param2, double param3){
doSomething();
}
public double apply(Object param1, Object param2, Object param3, double param4, double param5){
doSomething();
}
}
< /code>
When I create an array of objects of these classes and hard code them so I know which index has which class, when I try to call the apply function with 5 arguments, I get the error Expected 3 arguments but found 5
Code: Select all
public class Class1 {
objects = new CommmonInterface[2];
objects[1] = new CommonClass();
objects[2] = new DifferentClass();
objects[1].apply(arg1, arg2, arg3);
objects[2].apply(arg1, arg2, arg3); // Works
objects[2].apply(arg1, arg2, arg3, arg4, arg5); // Error
< /code>
I am not too sure why trying to overload the function does not work here. Is it not working because the DifferentClass