Let me describe the situation, and I’m sure I’m just thinking about this problem incorrectly. I have a concrete class that will implement an interface. I want to enforce in the contract that the class must have a constructor with a specific type. So for instance:
interface MyInterface {}
public class MyClass implements MyInterface {
public MyClass(HashMap<String, String> params) {
}
}
I want to ensure that MyClass is instantiated with a single HashMap argument, which seems like it would be done something like this:
interface MyInterface<T>
Other than using generics on method signatures, I’ve never used them with classes or interfaces, and I’m really a beginner with that, so please explain any generics involved with the solution… or the alternative solution if I’m thinking about this incorrectly (architecturally speaking). Thanks!
You can’t enforce a contract on constructor using interface in Java. The best approximation you could get is by defining an interface for a factory, with a
create()method that takes a singleHashMap…Also you can replace the interface with an abstract class for which the constructor requires an
HashMap, that will force sub classes to give one, but not more (the sub classes will not necessarily have an HashMap parameter).