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

查看:168
本文介绍了为什么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);
    }
}

在这种情况下,制作课程是有意义的抽象和最终。摘要因为制作这个类的对象没有用,因为所有方法都可以静态访问。最后因为派生类不能从该类继承任何东西,因为它没有任何非静态成员。

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#允许静态修饰符类。为什么Java不支持这个?

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

推荐答案

一个 final 类可以不能扩展,抽象需要进行扩展才能实例化。因此,最终抽象类将是一个逻辑矛盾。

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天全站免登陆