何时将 Java 中的内部类用于辅助类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18396016/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 01:12:28  来源:igfitidea点击:

When to use inner classes in Java for helper classes

javainner-classes

提问by Hild

If I have for example a class along with a helper class to do some of its functionality, does it make sense to make it as an inner class.

例如,如果我有一个类和一个辅助类来执行其某些功能,那么将其作为内部类是否有意义。

    public class Foo {
       private FooHelper helper;

       // constructor & any other logic

       public void doSomeThing() {
         helper.do();
       }
    }

    public class FooHelper {
        public void do() {
         // code
        }
    }

In the above case does it make sense to make the FooHelperas an inner class ? Apology if this sound stupid but I am little confused about the use cases.

在上述情况下,将FooHelper设为内部类是否有意义?道歉,如果这听起来很愚蠢,但我对用例有点困惑。

采纳答案by MD Sayem Ahmed

Yes, it makes perfect sense to make it an inner class. If no other classes need it, make it private. If it doesn't require exclusive access to the members of the outer class, make it a static nested class because then it will require less memory space.

是的,让它成为内部类是完全合理的。如果没有其他类需要它,请将其设为私有。如果它不需要对外部类的成员进行独占访问,请将其设为静态嵌套类,因为这样将需要较少的内存空间。

Check out the recommendation from the official tutorial-

查看官方教程中的推荐——

Use a non-static nested class (or inner class) if you require access to an enclosing instance's non-public fields and methods. Use a static nested class if you don't require this access.

如果您需要访问封闭实例的非公共字段和方法,请使用非静态嵌套类(或内部类)。如果您不需要此访问权限,请使用静态嵌套类。

回答by sanbhat

If you think that FooHelperwill not at all be usefulfor other classes than Foo, then it makes sense to make it as privateinner classof Foo. One example of this kind of design can be found in HashMapwhere it defines a private inner class KeySet

如果你认为FooHelper不会在所有有用的其他类比Foo,话很有道理,使其作为private内部类Foo。这种设计的一个例子可以HashMap在它定义私有内部类的地方找到KeySet

Otherwise having it as a privateinstance looks good.

否则将其作为private实例看起来不错。

回答by code_fish

Inner classes make sense when they are tiny and don't need names. Listeners in GUIs are classic examples where they make sense.

当内部类很小并且不需要名称时,它们才有意义。GUI 中的侦听器是有意义的经典示例。

If the class is big and important, it should be named and placed in a separate file.

如果这个类很大很重要,它应该被命名并放在一个单独的文件中。

The listener classes in normal GUI examples do one tiny thing, usually just dispatch to some other function to do real work.

普通 GUI 示例中的侦听器类做一件小事,通常只是分派到其他一些函数来做实际工作。

I also often use static nested classes (which are technically not inner classes) for classes which are only used in the context of another class - Map.Entryis a good example of this. It's only used in conjunction with a Map, so having the definition of Entry be a part of the Map interface makes organizational sense.

我也经常将静态嵌套类(技术上不是内部类)用于仅在另一个类的上下文中使用的类 - Map.Entry就是一个很好的例子。它仅与 Map 结合使用,因此将 Entry 的定义作为 Map 界面的一部分具有组织意义。

I don't generally have much use for other types of nested classes, like nonstatic member classes and local classes. But they do occasionally come in useful. For a good example of a legitimate use for member classes, see the source code for LinkedList.ListItr. This is a private inner class whose purpose is to provide an implementation of ListIteratorfor a LinkedList. To do this, it's useful to have access to the private data inside the LinkedList. To achieve this using only top-level classes, it would have been necessary to expose more public methods in LinkedList to allow the ListIterator to get at the underlying implementation of the LinkedList. Instead, using an inner class allows LinkedList to keep its implementation private, as it should be.

我通常对其他类型的嵌套类没有太多用处,比如非静态成员类和本地类。但它们偶尔会派上用场。有关合法使用成员类的一个很好的示例,请参阅 LinkedList.ListItr 的源代码。这是一个私有内部类,其目的是为LinkedList提供ListIterator的实现。为此,访问 LinkedList 中的私有数据很有用。为了仅使用顶级类实现这一点,有必要在 LinkedList 中公开更多公共方法,以允许 ListIterator 获取 LinkedList 的底层实现。相反,使用内部类允许 LinkedList 保持其实现私有,因为它应该是。

回答by Malwaregeek

Yes, the advantage of using inner class is it can access members of outer class.In your case , if you think your FooHelperis not to be used by any other class,you can make it a inner class.

是的,使用内部类的好处是它可以访问外部类的成员。在你的情况下,如果你认为你FooHelper的不被任何其他类使用,你可以把它变成一个内部类。

To check out the utility of inner class, go through the examples of AWT. Anonymous inner classes are widely used in event handlers.

要查看内部类的实用程序,请查看 AWT 的示例。匿名内部类广泛用于事件处理程序。

回答by Martin Podval

What is Foo's scope? When Foois domain model classwith it's own lifecycle and helperis common service, seems like mixing of two objects with very different scope/lifecycle.

什么是Foo的范围是什么?如果Foo域模型类与它自己的生命周期,helper是普通的业务,似乎是非常不同的范围/生命周期的两个对象的混合。

Typically domain entity has it's own lifecycle from creation, persistence to it's GC. On the other hand, helper or service is either static or better dynamicwith lifecycle equals to the whole app, e.g. spring bean.

通常,域实体从创建、持久化到 GC 都有自己的生命周期。另一方面,助手或服务要么是静态的,要么是更好的动态,生命周期等于整个应用程序,例如 spring bean。

Once your domain entity would contain reference of a service it can bring you serious problems. E.g. every call to repository's Getneeds to inject reference of this service into domain entity. I'd recommend to avoid this pattern.

一旦您的域实体包含服务的引用,它就会给您带来严重的问题。例如,对存储库的每次调用都Get需要将此服务的引用注入到域实体中。我建议避免这种模式。

It's not apparent for me who will make instance of Helperfor you.

我不清楚谁会Helper为你举个例子。

回答by Ashwani

Here are some uses of inner classes.

以下是内部类的一些用途。

  • Inner classes are used to get functionality which can get an object better than method.
  • They can be used in the case when a set of multiple operations are required and chances of reusability are good inside the class and they will not be accessed but methods outside the outer class.
  • Inner classes are made to achieve multiple inheritance also.
  • Inner classes are used when they are useful in class context.
  • They are used to separate logic inside classes.
  • 内部类用于获取可以比方法更好地获取对象的功能。
  • 当需要一组多个操作并且在类内部重用的机会很好并且不会访问它们而是外部类之外的方法时,可以使用它们。
  • 内部类也被用来实现多重继承。
  • 内部类在类上下文中有用时使用。
  • 它们用于分离类内部的逻辑。

So if you have some requirement matching above points than inner classes can be used. It is always better to make inner class privateto prevent access from other classes. In your case use of inner classes is helpful to make code readable and separate logic in the outer class.

因此,如果您有一些与上述点匹配的​​要求,则可以使用内部类。最好是创建内部类private以防止其他类访问。在您的情况下,使用内部类有助于使外部类中的代码可读和分离逻辑。

回答by Ravindra Mijar

Hild, Yes, it makes sense to use an inner class in many cases.

Hild,是的,在很多情况下使用内部类是有意义的。

Think of it this way - the inner class will live and die with the outer class, so any functionality that is specifically needed for the outer class can be added to the inner class. Popular examples are - Listeners in most cases - Types of KeyListeners, MouseListeners, eventListeners.

这样想 - 内部类将与外部类一起生存和消亡,因此外部类特别需要的任何功能都可以添加到内部类中。流行的例子是 - 大多数情况下的侦听器 - KeyListeners、MouseListeners、eventListeners 的类型。

Classes in Java allow you to have specific functionality, but sometimes you may need to have a separate specialized functionality but it also needs to be intimately tied to the class you're designing.

Java 中的类允许您拥有特定的功能,但有时您可能需要拥有单独的专门功能,但它也需要与您正在设计的类密切相关。

There can be four types of inner classes. A simple google search can help you to find out more about them.

可以有四种类型的内部类。一个简单的谷歌搜索可以帮助您找到更多关于它们的信息。

回答by Rahul Maurya

Nested Classes,enable you to logically group classes that are only used in one place, increase the use of encapsulation, and create more readable and maintainable code. Local classes, anonymous classes.

嵌套类,让你可以对只在一个地方使用的类进行逻辑分组,增加封装的使用,并创建更具可读性和可维护性的代码。本地类,匿名类。

http://docs.oracle.com/javase/tutorial/java/javaOO/whentouse.html

http://docs.oracle.com/javase/tutorial/java/javaOO/whentouse.html

回答by Premraj

When to use inner classes?

什么时候使用内部类?

  1. Inner class does not need any additional or separate file to place.
  2. Inner classes are comparatively small and tightly coupled with the “parent” class or “outer” class. Avoids lot of helper classesand fits to explain the OOD principle of containment.
  3. All the code in the same file increases readability and increases performance (like online code). Their importance is growing in the coding and treated as a good practice.
  4. Anonymous inner classes are very useful when you want to define callbacks on the fly.
  5. An object of an inner class can access the implementation of the object that created it- INCLUDING private data.
  6. Inner classes are capable of accessing the behavior of their parent class including private.
  1. 内部类不需要放置任何额外或单独的文件。
  2. 内部类相对较小,并且与“父”类或“外部”类紧密耦合。避免了很多辅助类,适合解释包含的 OOD 原则。
  3. 同一文件中的所有代码提高了可读性并提高了性能(如在线代码)。它们在编码中的重要性正在增长,并被视为一种良好的做法。
  4. 当您想动态定义回调时,匿名内部类非常有用。
  5. 内部类的对象可以访问创建它的对象的实现——包括私有数据。
  6. 内部类能够访问其父类的行为,包括私有的。

回答by ChandraBhan Singh

From JAVA SE Docs

来自 JAVA SE 文档

Why Use Nested Classes?

为什么使用嵌套类?

It is a way of logically grouping classes that are only used in one place:If a class is useful to only one other class, then it is logical to embed it in that class and keep the two together. Nesting such "helper classes" makes their package more streamlined.

这是一种对只在一个地方使用的类进行逻辑分组的方法:如果一个类只对另一个类有用,那么将它嵌入到该类中并将两者保持在一起是合乎逻辑的。嵌套这样的“辅助类”使它们的包更加精简。

It increases encapsulation:Consider two top-level classes, A and B, where B needs access to members of A that would otherwise be declared private. By hiding class B within class A, A's members can be declared private and B can access them. In addition, B itself can be hidden from the outside world.

它增加了封装性:考虑两个顶级类 A 和 B,其中 B 需要访问 A 的成员,否则这些成员将被声明为私有。通过将 B 类隐藏在 A 类中,A 的成员可以被声明为私有,而 B 可以访问它们。此外,B 本身可以对外界隐藏。

So Yes, it makes sense to use FooHelperas an inner class.

所以是的,使用FooHelper作为内部类是有意义的。