为什么静态类在 Java 中是非法的? [英] Why is a static class illegal in Java?

查看:37
本文介绍了为什么静态类在 Java 中是非法的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm developing an Android application but have hit a bit of a brick wall, I keep getting the error:

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

这是在跟随 this answer 到另一个 SO 问题之后发生的.这是我拥有的代码:

This happened after following this answer to another SO question. Here is the code that I have:

package com.package.name;

/* Imports were here */

public static class FavsPopupFragment extends SherlockDialogFragment {

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

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

The error appears on the class name. I don't understand why this won't work, please help. Thank you.

推荐答案

您不能创建顶级静态类;这就是编译器试图告诉你的.另请查看此处的答案,了解为什么会出现这种情况.要点是:

You can't create a top level static class; that's what the compiler is trying to tell you. Also have a look at the answer here as to why this is the case. The gist is:

静态归结为类的实例可以独立存在.或者,反过来:非静态内部类(= 实例内部类)没有外部的实例就不能存在班级.由于顶级类没有外部类,因此不能绝不是静态的.

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 中是非法的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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