Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An interface with different method parameters

I want to declare an interface be use with several classes
this classes have method with different parameters

interface:

public interface Operation {

public int Add();

}

class A:

public class CLASSA implement Operation{

     public int Add(int id,String name);

}

class B:

public class CLASSB implement Operation{

     public int Add(String name);

}

how to impelement of this interface?

like image 478
user1874800 Avatar asked Feb 17 '13 13:02

user1874800


People also ask

CAN interface have different parameters?

Overloading methods of an interfaceYes, you can have overloaded methods (methods with the same name different parameters) in an interface. You can implement this interface and achieve method overloading through its methods.

Can an interface have multiple methods?

Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class. An interface can contain any number of methods.

What are the different methods of interface?

The interface body can contain abstract methods, default methods, and static methods. An abstract method within an interface is followed by a semicolon, but no braces (an abstract method does not contain an implementation).

How many methods can a interface have?

At present, a Java interface can have up to six different types. Interfaces cannot be instantiated, but rather are implemented. A class that implements an interface must implement all of the non-default methods described in the interface, or be an abstract class.


2 Answers

you could make an operand-object

public interface Operation {

public int Add(Operand o);

}

or

public interface Operation {

 public int Add(Operand... o);

}
like image 101
El Hocko Avatar answered Sep 23 '22 17:09

El Hocko


A few points worth mentioning regarding the other answers:

  • Having and interface with multiple function implementation (one for each set of arguments) violates the interface segregation principle.
  • Making the class ignore the unused arguments violates the Liskov substitution principle.

My suggestion would be to implement something like the Command pattern. To decouple the command implementation from its implementations is precisely its intent.

like image 33
Michael Gruner Avatar answered Sep 26 '22 17:09

Michael Gruner