Java中的模块化:顶级类与嵌套类 [英] Modularity in Java: top level vs. nested classes

查看:173
本文介绍了Java中的模块化:顶级类与嵌套类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读的Java教程喜欢使用嵌套类来演示概念,功能或用法.

The Java tutorials that I read, like to use nested classes to demonstrate a concept, a feature or use.

这导致我最初实施了一个我创建的示例项目,即:主要活动类中有许多嵌套类.

This led me to initially implement a sample project I created just like that: Lots of nested classes in the main activity class.

它可以工作,但是现在我得到了一个巨大的整体式.java文件.我觉得有些不便,现在打算分解为多个.java文件/类.

It works, but now I got a monstrous monolithic .java file. I find it somewhat inconvenient and I now intend to break to multiple .java files/classes.

但是,我想到,有时可能出于某些原因将类从其封闭类中移除.

It occurred to me, however, that sometimes there may be reasons not to take classes out of their enclosing class.

如果是的话,考虑到模块性和易于维护性,有什么理由使模块保持较大尺寸?

If so, what are good reasons to keep a module large, considering modularity and ease of maintenance?

是否存在将嵌套类转换为顶级类不切实际(甚至不可能)的情况?换句话说,是否只有嵌套类才能满足某些功能?

Are there cases in which it is impractical (or even impossible) to convert a nested class to a toplevel class? In other words, is there a case in which only a nested class could satisfy certain functionality?

推荐答案

一个非静态嵌套类对隐含类的创建者实例具有隐式引用,并且它还可以访问该隐含类的每个成员(甚至私有).成员).如果将嵌套类设为顶级,则会丢失此信息:

a non-static nested class has an implicit reference to the creator instance of the enclosing class, and also it can access every member of the enclosing class (even private members). You lose this if you make the nested class top-level:

public class Outer {
    private String s;

    public void setS(String s) {
        this.s = s;
    }

    public class Inner {
        public String getOuterS() {
            // This is legal only if Inner is
            // non-static and nested in Outer
            return s;
        }
    }
}

public class Main {
    public static void main(String[] args) {
        Outer o = new Outer();
        o.setS("Hello world!!!");

        // i now has access to every o member
        Outer.Inner i = o.new Inner();

        // Prints "Hello world!!!"
        System.out.println(i.getOuterS());
    }
}

这篇关于Java中的模块化:顶级类与嵌套类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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