0

I want to have an interface that allows me to use methods with optional parameters. Suppose I have an interface:

public interface Stuff {
    public int Add();
 }

And I have two classes A and B who implement the interface. One method needs parameter, but the other one doesn't.

public class CLASS A implements Stuff{
    public int Add();
}  


public class CLASS B implements Stuff{
    public int Add(String name);
}

How can I achieve this?

kevin
  • 419
  • 1
  • 3
  • 11
  • What's the point in having the interface if the parameters aren't the same? You wouldn't be able to call the method on the interface because the compiler wouldn't know what set of arguments to use. Might as well get rid of the interface. Please explain what behavior you want from this "interface", rather than just saying you want an interface that does "this". – Charlie Armstrong Jan 13 '21 at 18:32
  • I think varargs is what you're looking for – lorraine batol Jan 13 '21 at 18:38
  • @villager Even with varargs, you can't change the parameter list. A better idea would be to just always have a String parameter, and ignore it when you don't need it. Varargs is supposed to be a convenient way to pass in an array of objects, it's not really an "optional" parameter. – Charlie Armstrong Jan 13 '21 at 18:43

1 Answers1

-3

I think You have to override function.

You can read about that here => https://www.geeksforgeeks.org/overriding-in-java/

  • This doesn't address the question whatsoever. The whole point of overriding a method is that it keeps the method header, but lets you change the method body. If the parameters change, then you've changed the method header, and you're no longer overriding that method. – Charlie Armstrong Jan 13 '21 at 18:39