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

问题描述

到处都找不到满意的答案.

Can't find a satisfactory answer anywhere.

推荐答案

根据定义,所有顶级类都是静态的.

All top-level classes are, by definition, static.

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

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.

因为所有顶级类都是静态的,在顶级类定义中使用 static 关键字是没有意义的.

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

一些可以玩的代码:

public class Foo {

    public class Bar {
         // Non-static innner class
    }

    public static class Baz {
         // Static inner class
    }
}

public class Example {
    public static void main(String[] args) {
        new Foo(); // this is ok
        new Foo.Baz(); // this is ok
        new Foo.Bar(); // does not compile!

        Foo f = new Foo();
        Foo.Bar bar = f.new Bar(); //this works, but don't do this
    }
}

我把但不要这样做"放在那里,因为它真的代码设计很丑.实例内部类不应在外部类之外可见.它们只能在外部类中使用.

I put the "but don't do this" in there because it's really ugly code design. Instance inner classes should not be visible outside the outer class. They should only be used from within the outer class.

这篇关于为什么顶级类在 Java 中不能是静态的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 08:06