何时在Java中使用辅助类的内部类 [英] When to use inner classes in Java for helper classes

查看:57
本文介绍了何时在Java中使用辅助类的内部类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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
        }
    }

在上述情况下,使 FooHelper 作为一个内部阶级?道歉,如果这听起来很愚蠢,但我对用例感到困惑。

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

推荐答案

是的,让它成为一个完美的意义内心阶级。如果没有其他类需要它,请将其设为私有。如果它不需要独占访问外部类的成员,那么使它成为一个静态嵌套类,因为它将需要更少的内存空间。

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.

这篇关于何时在Java中使用辅助类的内部类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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