JAVA继承可以继承多个吗_java – 多个继承的类,它们必须在单独的文件中吗?

我正在实现一个系统,我有一个名为’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,oop,inheritance,methods

来源: https://codeday.me/bug/20190826/1725271.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值