java - 为什么静态类在 Java 中是非法的?

标签 java static static-classes

我正在开发一个 Android 应用程序,但遇到了一些问题,我不断收到错误消息:

Illegal modifier for the class FavsPopupFragment; only public, abstract & final are permitted

这发生在关注 this answer 之后另一个SO问题。这是我的代码:

package com.package.name;

/* Imports were here */

public static class FavsPopupFragment extends SherlockDialogFragment {

    static FavsPopupFragment newInstance() {
        FavsPopupFragment frag = new FavsPopupFragment();
        return frag;
    }
}

错误出现在类名上。我不明白为什么这不起作用,请帮助。谢谢。

最佳答案

您不能创建顶级静态类;这就是编译器试图告诉你的。也看看答案here至于为什么会这样。要点是:

What the static boils down to is that an instance of the class can stand on its own. Or, the other way around: a non-static inner class (= instance inner class) cannot exist without an instance of the outer class. Since a top-level class does not have an outer class, it can't be anything but static.

Because all top-level classes are static, having the static keyword in a top-level class definition is pointless.

关于java - 为什么静态类在 Java 中是非法的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11831791/

相关文章:

Java 11.javac/警告 : [options] module name in --add-reads option not found: moduleB

java - 给定经纬度坐标,如何打印两个城市之间的距离?

language-agnostic - 什么时候方法应该是静态的?

模板中的 C++ 静态常量初始化顺序

java - 检查是否声明了静态类(使用反射)

java - 在构造函数中初始化公共(public)静态最终变量

java - 我该怎么办 session URL 很长,我无法附加 JSESSIONID=389729387392。解决方案是什么?

java - 如何解析 SOAP 响应

c - 为什么要在 C 中声明变量或函数静态?

static-classes - 你应该避免静态类吗?