为什么顶层类在Java中不能是静态的? [英] Why can't a top level class be static in Java?

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

问题描述

任何地方找不到满意的答案。

解决方案

根据定义,所有顶级类都是静态的。 / p>

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



由于所有顶级类都是静态的,在顶级类定义中使用 static 关键字是无意义的。



一些代码:

  public class Foo {

public class Bar {
//非静态内部类
}

public static class Baz {
//静态内部类
}
}

public class示例{
public static void main(String [] args){
new Foo(); // this is ok
new Foo.Baz(); // this is ok
new Foo.Bar(); //不编译!

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

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


Can't find a satisfactory answer anywhere.

解决方案

All top-level classes are, by definition, 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.

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

Some code to play around with:

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

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