Java最终抽象类 [英] Java final abstract class

查看:132
本文介绍了Java最终抽象类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很简单的问题:

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...

我讨厌解决方法。

推荐答案

参考:有效的Java第2版第4项强制不可否定性与私有构造函数

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆