Pet*_*aný 23
还有两个选择:
使每个方法最终,所以人们不能覆盖它们.您可以避免以这种方式从子类中意外调用方法.但这并不会阻止子类化.
把检查放入类的构造函数中:
if (this.getClass() != MyClass.class) {
throw new RuntimeException("Subclasses not allowed");
}
Run Code Online (Sandbox Code Playgroud)
然后没人能够实例化你的类的子类.
(不是我建议使用这些技术,它只是出现在我的脑海里.我将使用final类和/或私有构造函数)
使用评论:
// do not inherit
Run Code Online (Sandbox Code Playgroud)使用javadoc评论
在类构造函数中使用运行时检查:
if (this.getClass() != MyClass.class) {
throw new RuntimeException("Subclasses not allowed");
}
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
12458 次 |
| 最近记录: |