Java最终抽象类 [英] Java final abstract class
问题描述
我有一个很简单的问题:
I have a quite simple question:
我想要一个 Java 类,它提供一个公共静态方法,它可以做一些事情.这只是为了封装的目的(将所有重要的东西都放在一个单独的类中)...
I want to have a Java Class, which provides one public static method, which does something. This is just for encapsulating purposes (to have everything important within one separate class)...
这个类既不应该被实例化,也不应该被扩展.这让我写道:
This class should neither be instantiated, nor being extended. That made me write:
final abstract class MyClass {
static void myMethod() {
...
}
... // More private methods and fields...
}
(虽然我知道,这是被禁止的).
(though I knew, it is forbidden).
我也知道,我可以使这个类完全成为最终类,并在使其私有的同时覆盖标准构造函数.
I also know, that I can make this class solely final and override the standard constructor while making it private.
但这在我看来更像是一种解决方法",应该更有可能由最终抽象类来完成...
But this seems to me more like a "Workaround" and SHOULD more likely be done by final abstract class...
而且我讨厌变通办法.所以只是为了我自己的兴趣:还有其他更好的方法吗?
And I hate workarounds. So just for my own interest: Is there another, better way?
推荐答案
参考:Effective Java 2nd Edition Item 4Enforce noninstantiability with a private constructor"
Reference: Effective Java 2nd Edition Item 4 "Enforce noninstantiability with a private constructor"
public final class MyClass { //final not required but clearly states intention
//private default constructor ==> can't be instantiated
//side effect: class is final because it can't be subclassed:
//super() can't be called from subclasses
private MyClass() {
throw new AssertionError()
}
//...
public static void doSomething() {}
}
这篇关于Java最终抽象类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!