有什么方法可以在Java类中强制执行特定的构造函数?
例如,我希望从类继承的所有类都具有类似-的构造函数。
public classname(string s1,string s2){....}
我知道不应该避免它,因为它可能导致多重继承的问题。但是有办法吗?
Java中没有任何工具可以直接执行此操作。
但是,可以使用某种abstract
方法将其强制执行。
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) {
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句