Reputation: 328
Is there any way to enforce a specific constructor in Java classes?
For example I want all classes that inherit from a Class to have a constructor like -
public classname(string s1,string s2){....}
I know it should not be avoided because it can lead to problems with multiple inheritance. But is there a way to do it anyway?
Upvotes: 1
Views: 487
Reputation: 3151
Sorry, but no, you cannot force classes to only implement a specific constructor.
Upvotes: -1
Reputation: 65813
There are no facilities in Java to do that directly.
However, it can be enforced to some extent usin an abstract
method.
abstract class Base {
Base(String s1, String s2) {
init(s1, s2);
}
protected abstract void init(String s1, String s2);
}
class MyClass extends Base {
// Forced to do this.
MyClass() {
super("One", "Two");
}
// Forced to do this.
@Override
protected void init(String s1, String s2) {
}
}
Upvotes: 4
Reputation: 109547
You want that there is only one constructor, and that with the same signature. That could in a costly way done with reflection, at run-time.
public BaseClass(String s, String t, int n) {
Class<?> cl = getClass();
do {
check(cl);
cl = cl.getSuperclass();
} while (cl != BaseClass.class);
}
private void check(Class<?> cl) {
if (cl.getConstructors().length != 1) {
throw new IllegalStateException("Needs only 1 constructor in: " + cl.getName());
}
try {
cl.getConstructor(String.class, String.class, int.class);
} catch (NoSuchMethodException e) {
throw new IllegalStateException("Constructor should have parameter types (String, String, int) in: " + cl.getName());
}
}
Not advisable
However you could make a factory to be used that hides class hierarchies. Or in fact use a single class that delegates to your class hierarchy (has a member of your class).
Upvotes: 3