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

问题描述

我想问你为什么我们需要内部类以及为什么我们使用它们?

我知道如何使用内部类,但我不知道为什么..

I want to ask you why we need inner classes and why we use them ?
I know how to use inner classes but I don't know why..

推荐答案

内部类是公开的(例如,Java中的 Map.Entry ),但这是例外而不是常态。

Some inner classes are exposed publicly (eg Map.Entry in Java) but that is by far the exception rather than the norm.

内部类基本上是一个实现细节。

Inner classes are, basically, an implementation detail.

例如,Swing广泛使用内部类用于事件监听器。如果没有它们,你最终会用一堆你不需要看的类来污染全局命名空间(这可能会使它们的目的更难确定)。

For example, Swing makes extensive use of inner classes for event listeners. Without them you would end up polluting the global namespace with a bunch of classes you otherwise don't need to see (which may make their purpose harder to determine).

基本上内部类是范围的一种形式。包访问会从包外部隐藏类。私有内部类从该类外部隐藏该类。

Essentially inner classes are a form of scope. Package access hides classes from outside the package. Private inner classes hide that class from outside that class.

Java中的内部类也可以替代缺少函数指针或方法委托(在C#中)或关闭。它们是将函数传递给另一个函数的手段。例如,在 Executor 类中,您有:

Inner classes in Java are also a substitute for a lack of function pointers or method delegates (which are in C#) or closures. They are the means of passing a function to another function. For example, in the Executor class you have:

void execute(Runnable r);

所以你可以传入一个方法。在C / C ++中可以通过以下方式实现:

so you can pass a method in. In C/C++ that could be achieved with:

void execute(void (*run)());

是指向函数的指针。

这篇关于为什么我们使用内部类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 14:26