什么是静态嵌套类

什么是静态嵌套类

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

问题描述





静态和非静态嵌套类之间的区别是什么?

What is a static nested class?What is the difference between static and non-static nested classes?

推荐答案

静态内部类是嵌套的类在另一个具有 static 修饰符的类中。它与顶级类几乎完全相同,除了它可以访问其内部定义的类的私有成员。

A static inner class is a class nested inside another class that has the static modifier. It's pretty much identical to a top-level class, except it has access to the private members of the class it's defined inside of.

class Outer {
    private static int x;
    static class Inner1 {
    }
    class Inner2 {
    }
}

Class Inner1 是一个静态内部类。 Class Inner2 是一个非静态的内部类。两者之间的区别在于,非静态内部类的实例永久地附加到 Outer 的实例 - 您无法创建 Inner2 没有 Outer 。不过,您可以单独创建 Inner1 对象。

Class Inner1 is a static inner class. Class Inner2 is an inner class that's not static. The difference between the two is that instances of the non-static inner class are permanently attached to an instance of Outer -- you can't create an Inner2 without an Outer. You can create Inner1 object independently, though.

中的代码 Inner1 Inner2 都可以访问x;不允许其他代码。

Code in Outer, Inner1 and Inner2 can all access x; no other code will be allowed to.

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

08-14 06:04