本文介绍了java强制扩展类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Java 中,我能否以某种方式强制扩展抽象类的类以对象作为参数实现其构造函数?
In Java, can I somehow force a class that extends an abstract class to implement its constructor with a Object as a parameter?
类似的东西
public abstract class Points {
//add some abstract method to force constructor to have object.
}
public class ExtendPoints extends Points {
/**
* I want the abstract class to force this implementation to have
* a constructor with an object in it?
* @param o
*/
public ExtendPoints(Object o){
}
}
推荐答案
您可以在抽象类中使用带有参数的构造函数(如果您想禁止匿名子类,请使其受保护).
You can use a constructor with a parameter in your abstract class (make it protected if you want to dis-allow anonymous subclasses).
public abstract class Points{
protected Points(Something parameter){
// do something with parameter
}
}
这样做,您会强制实现类具有显式构造函数,因为它必须使用一个参数调用超级构造函数.
Doing that, you force the implementing class to have an explicit constructor, as it must call the super constructor with one parameter.
但是,您不能强制覆盖类具有带参数的构造函数.它总是可以像这样伪造参数:
However, you cannot force the overriding class to have a constructor with parameters. It can always fake the parameter like this:
public class ExtendPoints extends Points{
public ExtendPoints(){
super(something);
}
}
这篇关于java强制扩展类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!