本文介绍了同一文件中的Java公共接口和公共类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在单个.Java文件中,是否可以拥有公共接口和公共类(实现接口)

In a single .Java file, is it possible to have a public interface and a public class (which implements the interface)

我是Java编码的新手并且在网上的大多数地方写的.java文件不能包含超过2个公共类。我想知道接口和类是否也是如此。

I'm new to Java coding and it is written on most places on the net that a .java file cannot contain more than 2 public class. I want to know if it is true for the interface and a class also.

推荐答案

不,这是不可能的。每个 .java 文件最多可能有一个顶级公共类型。 声明如下:

No, it's not possible. There may be at most one top-level public type per .java file. JLS 7.6. Top Level Type Declarations states the following:

但是,您可以在同一个文件中拥有受包保护的类。这个编译很好(如果你把它放在一个名为 Test.java 的文件中:

You could however have a package-protected class in the same file. This compiles fine (if you put it in a file named Test.java:

public interface Test {
    // ...
}

class TestClass implements Test {
    // ...
}

这篇关于同一文件中的Java公共接口和公共类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-29 06:53
查看更多