java – 多个继承的类,它们必须在单独的文件中吗?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java – 多个继承的类,它们必须在单独的文件中吗?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2189字,纯文字阅读大概需要4分钟。
内容图文
![java – 多个继承的类,它们必须在单独的文件中吗?](/upload/InfoBanner/zyjiaocheng/731/7f7bb2b65a724f61bff870934cf65fd7.jpg)
我正在实现一个系统,我有一个名为’MyMethod’的接口(名称是任意的),许多小类正在实现这个方法(特别是覆盖它的’call’方法),我正在使用多态来创建将这些实例放入列表中.
问题是,由于我有许多实现该方法的小类,因此将这些类放在同一个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中应该完成的事情.
将这些类放在同一个文件中是否可以?或者我应该将它们分别移动到单独的文件中?
谢谢
解决方法:
是的,可以将几个包私有类放在同一个文件中.
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 (07002), 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编译单元之外不可用,具体取决于编译器实现.虽然,javac和Eclipse编译器似乎都没有这个问题……
内容总结
以上是互联网集市为您收集整理的java – 多个继承的类,它们必须在单独的文件中吗?全部内容,希望文章能够帮你解决java – 多个继承的类,它们必须在单独的文件中吗?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。