Java:在一个文件中有多个类声明 [英] Java: Multiple class declarations in one file

查看:125
本文介绍了Java:在一个文件中有多个类声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,您可以在单个文件中定义多个顶级类,但最多只能有一个是public的(请参阅 JLS§7.6)。

In Java, you can define multiple top level classes in a single file, providing that at most one of these is public (see JLS §7.6). See below for example.


  1. 这种技术有一个整洁的名称(类似于 inner 嵌套 anonymous )?

JLS表示系统可能强制实施这些限制,即这些辅助类不能由程序包的其他编译单元中的代码引用,例如,它们不能被视为包私有。这是真的在Java实现之间改变的东西吗?

The JLS says the system may enforce the restriction that these secondary classes can't be referred to by code in other compilation units of the package, e.g., they can't be treated as package-private. Is that really something that changes between Java implementations?

例如PublicClass.java:

e.g., PublicClass.java:

package com.example.multiple;

public class PublicClass {
    PrivateImpl impl = new PrivateImpl();
}

class PrivateImpl {
    int implementationData;
}


推荐答案

(包括单个源文件中的多个顶级类)将是混乱。认真的,我不认为这是一个好主意 - 我会在这种情况下使用嵌套类型。然后它仍然很容易预测其中的源文件。我不相信这个方法的官方术语。

My suggested name for this technique (including multiple top-level classes in a single source file) would be "mess". Seriously, I don't think it's a good idea - I'd use a nested type in this situation instead. Then it's still easy to predict which source file it's in. I don't believe there's an official term for this approach though.

至于这是否实际上改变之间实现 - 我非常怀疑,但如果你避免这样做,你永远不需要关心:)

As for whether this actually changes between implementations - I highly doubt it, but if you avoid doing it in the first place, you'll never need to care :)

这篇关于Java:在一个文件中有多个类声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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