为什么 Java 类不能既是抽象类又是最终类 [英] Why can't a Java class be both abstract and final

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

问题描述

假设我有一个仅包含静态方法和变量的实用程序类.例如:

Suppose I've a utility class which contains only static methods and variables. e.g:

public abstract final class StringUtils
{
    public static final String NEW_LINE = System.getProperty("line.separator");

    public static boolean isNotNullOrSpace(final String string)
    {
        return !(string == null || string.length() < 1 || string.trim().length() < 1);
    }
}

在这种情况下,使类既抽象又最终是有意义的.抽象是因为创建此类的对象将没有用,因为所有方法都可以静态访问.Final 因为派生类不能从这个类继承任何东西,因为它没有任何非静态成员.

In this scenario, it makes sense to make the class both abstract and final. Abstract because making an object of this class will be of no use as all methods are accessible statically. Final because the derived class cannot inherit anything from this class as it does not have any non-static member.

C# 允许对此类类使用 static 修饰符.为什么 Java 不支持这个?

C# allows static modifier for such classes. Why doesn't Java support this?

推荐答案

final 类不能扩展,abstract需要 被扩展以被实例化.因此,final abstract 类将是逻辑上的矛盾.

A final class can't be extended, an abstract class needs to be extended in order to be instantiated. Therefore, a final abstract class would be a logical contradiction.

如果你的类只有 static 方法,也许你应该隐藏它的构造函数,通过将它定义为 private.-

If your class just have static methods, maybe you should just hide its constructor, by defining it as private.-

private StringUtils() {
}

这篇关于为什么 Java 类不能既是抽象类又是最终类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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