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

查看:25
本文介绍了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天全站免登陆