Java中的静态嵌套类,为什么? [英] Static nested class in Java, why?

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

问题描述

我在查看 LinkedList 的Java代码,并注意到它使用了一个静态嵌套类 Entry

I was looking at the Java code for LinkedList and noticed that it made use of a static nested class, Entry.

public class LinkedList<E> ... {
...

 private static class Entry<E> { ... }

}

静态嵌套类,而不是正常的内部类?

What is the reason for using a static nested class, rather than an normal inner class?

我可以想到的唯一原因是,Entry不能访问实例变量,所以从OOP观点它有更好的封装。

The only reason I could think of, was that Entry doesn't have access to instance variables, so from an OOP point of view it has better encapsulation.

但我认为可能有其他原因,也许表现。可能是什么?

But I thought there might be other reasons, maybe performance. What might it be?

注意。我希望我的条款正确,我会称之为静态内部类,但我认为这是错误的: http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html

Note. I hope I have got my terms correct, I would have called it a static inner class, but I think this is wrong: http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html

推荐答案

您链接的Sun页面之间有一些关键的区别:

The Sun page you link to has some key differences between the two:


嵌套类是它的封闭类的成员。非静态嵌套类(内部类)可以访问封闭类的其他成员,即使它们被声明为私有。静态嵌套类无法访问包含类的其他成员。

...

A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class.
...

注意:静态嵌套类与实例它的外部类(和其他类)的成员就像任何其他顶级类。 实际上,静态嵌套类在行为上是顶级类,为了打包方便,它嵌套在另一个顶级类中。

Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.

没有必要 LinkedList.Entry 是顶级类,因为它只是 使用 LinkedList (还有一些其他接口也有名为 Entry 的静态嵌套类,例如 Map。 Entry - 相同的概念)。因为它不需要访问LinkedList的成员,所以它是静态的 - 这是一个更清洁的方法是有意义的。

There is no need for LinkedList.Entry to be top-level class as it is only used by LinkedList (there are some other interfaces that also have static nested classes named Entry, such as Map.Entry - same concept). And since it does not need access to LinkedList's members, it makes sense for it to be static - it's a much cleaner approach.

作为 Jon Skeet指出,我认为如果你使用一个嵌套类是一个更好的主意是开始它是静态的,然后决定是否真的需要根据您的用法是非静态的。

As Jon Skeet points out, I think it is a better idea if you are using a nested class is to start off with it being static, and then decide if it really needs to be non-static based on your usage.

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

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