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

问题描述

在java中,外部类可以是public,final,default或abstract。
为什么不像

In java, An outer class may be public, final, default or abstract.Why not Static like

Static static class MyClass {}

推荐答案

外部类已经是隐式静态的。

An outer class is already implicitly static.

非静态嵌套类意味着内部类隐含地引用其父类。

Non-static nested class (= inner class) means thats the inner class implicitly has a reference to its parent class.

这就是为什么对于嵌套类,你可以区分静态和非静态。这对外部类没有意义。

That's why, for nested class, you can distinguish between static and non-static. This does not make sense for outer classes.

这里是一个例子来了解静态/非静态嵌套类之间的区别。你应该明白为什么在外部类中没有意义。

Here is an example to understand the difference between static/non-static nested class. You should understand why it does not make sense in an outer class.

public class MyClass {

  private String anAttributeOfMyClass;

  private /*static*/ class MyInnerClass {

    public void foo() {
      /*
       * Here, I can access the attribute of the parent class
       * because I implicitly have a reference to it.
       * Try to make the nested class static an see the difference.
       */
      anAttributeOfMyClass.trim();
    }
  }

}

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

08-22 14:26