java强制扩展类 [英] java force an extending class
本文介绍了java强制扩展类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Java中,我可以不知何故强迫一个扩展抽象类的类来实现它的构造函数,一个Object作为参数?
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强制扩展类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文