gpt4 book ai didi

java - 多个继承类,它们必须在单独的文件中吗?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:50:41 25 4
gpt4 key购买 nike

我正在实现一个系统,其中我有一个名为“MyMethod”的接口(interface)(名称是任意的),许多小类正在实现这个方法(特别是覆盖它的“调用”方法),我正在使用多态性将这些实例创建到列表中。

问题是,因为我有很多实现该方法的小类,所以将这些类放在同一个 java 文件 (MyMethod.java) 中会更容易,如下所示:

public interface MyMethod {
public String call(foo param1, bar param2) throws SQLException, IOException;
}

class FooMethod1 implements MyMethod {
@Override
public String call(foo param1, bar param2) throws SQLException, IOException {
//Do Something
}
}

class FooMethod2 implements MyMethod {
@Override
public String call(foo param1, bar param2) throws SQLException, IOException {
//Do Something Different
}
}

然而,将这些类放在同一个文件中,虽然更整洁,但似乎我违背了在 Java 中应该做的事情。

将这些类放在同一个文件中可以吗?还是应该将它们分别移动到一个单独的文件中?

谢谢

最佳答案

是的,可以将多个包私有(private)类放在同一个文件中。

JLS 的相关部分是 §7.3

CompilationUnit:
PackageDeclaration[opt] ImportDeclarations[opt] TypeDeclarations[opt]

TypeDeclarations:
TypeDeclaration
TypeDeclarations TypeDeclaration

如您所见,一个编译单元可能有多个类型声明(或零个)。 JLS 的另一个相关部分是 §7.6 .它解释了从编译单元外部访问的那些类型声明与编译单元的文件名之间的相关性:

If and only if packages are stored in a file system (§7.2), the host system may choose to enforce the restriction that it is a compile-time error if a type is not found in a file under a name composed of the type name plus an extension (such as .java or .jav) if either of the following is true:

  • The type is referred to by code in other compilation units of the package in which the type is declared.

  • The type is declared public (and therefore is potentially accessible from code in other packages).

This restriction implies that there must be at most one such type per compilation unit. This restriction makes it easy for a Java compiler to find a named class within a package. In practice, many programmers choose to put each class or interface type in its own compilation unit, whether or not it is public or is referred to by code in other compilation units.

很明显,您的方法并不反对 Java,而且完全没问题。但是,请注意您的 MyMethod 实现可能在 MyMethod.java 编译单元之外不可用,具体取决于编译器实现。虽然,javacEclipse 编译器 似乎都没有这方面的问题...

关于java - 多个继承类,它们必须在单独的文件中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13582563/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com