Java内部类访问和最佳实践 [英] Java Inner Class Access and Best Practices

查看:66
本文介绍了Java内部类访问和最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道内部类可以访问外部类中的所有内容(因为它是该类的成员),但是反过来又如何呢?

I know that an inner class has access to everything in the outer class (because it's a member of that class) but what about the other way around?

  1. 外部类可以访问内部类中的私有变量和方法吗?

  1. Does the outer class have access to private variables and methods within an inner class?

我看过一些文章提到内部类应该是私有的,以便它们只能由外部类访问.这对内部类的可访问性有什么影响?

I've seen articles mentioning that inner classes should be private so that they are accessible only to the outer class. What does that do to the accessibility of that inner class?

涉及内部类时,处理访问级别的最佳实践是什么?我假设封装越多越好,但这是以牺牲可访问性为代价的吗?

What is best practices in dealing with access levels when it comes to your inner classes? I'm assuming more encapsulation the better but does that come at the expense of accessibility?

推荐答案

Effective Java(第二版)第22项:相对于非静态的静态成员,更喜欢使用静态成员".

This topic is covered in some detail by Effective Java (2nd edition) Item 22: "Favor static member classes over nonstatic".

简短摘要:

  1. 内部类不应具有对外部类实例的访问权限,除非需要该访问,即默认情况下,内部类应为static.为了获得技术性知识,Effective Java调用了这些 static成员类,而不是 inner class ,并使用了 nested class 一词来涵盖这两个静态成员.和非静态版本.
  2. 外部类始终有权访问其内部类的成员,即使这些成员为private.这样,内部类只能将自身公开给外部类.
  3. 内部类应该只为服务其外部类而存在."
  1. An inner class should not have access to an outer class instance, unless that access is required, i.e. inner classes should be static by default. To get technical, Effective Java calls these static member classes, as opposed to inner classes, and uses the term nested class to encompass both the static and nonstatic versions.
  2. An outer class always has access to the members of its inner classes, even when those members are private. In this way, an inner class can expose itself only to its outer class.
  3. "An inner class should exist only to serve its outer class."

就个人而言,我倾向于实现一个内部类,只要这样做允许内部类的构造函数为private,即当一个类只能从另一个(外部)类实例化时.任何其他封装,例如使整个内部类成为private,都是可取的.但是public内部类是完全可以接受的. Java中有很多示例,例如

Personally, I'm inclined to implement an inner class whenever doing so allows the inner class's constructors to be private, i.e. when a class can only be instantiated from one other (outer) class. Any additional encapsulation, such as making the entire inner class private, is desirable; but public inner classes are perfectly acceptable. There are many examples in Java, such as AbstractMap.SimpleEntry.

这篇关于Java内部类访问和最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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