java Java公共接口和公共类在同一个文件中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7133497/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java public interface and public class in same file
提问by Linda Peters
In a single .Java file, is it possible to have a public interface and a public class (which implements the interface)
在单个 .Java 文件中,是否可以有一个公共接口和一个公共类(实现该接口)
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 编码的新手,它写在网上的大多数地方,一个 .java 文件不能包含超过 2 个公共类。我想知道接口和类是否也是如此。
回答by aioobe
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:
不,这不可能。每个.java
文件最多可能有一个顶级公共类型。JLS 7.6。顶级类型声明声明如下:
[…] there must be at most one [top level public] type per compilation unit.
[...] 每个编译单元最多必须有一个 [顶级公共] 类型。
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
:
但是,您可以在同一个文件中包含受包保护的类。这编译得很好(如果你把它放在一个名为的文件中Test.java
:
public interface Test {
// ...
}
class TestClass implements Test {
// ...
}
回答by emboss
You can have as many public classes as you want in one file if you use nested classes. In your example:
如果您使用嵌套类,则可以在一个文件中包含任意数量的公共类。在你的例子中:
public interface I {
public class C implements I {
...
}
public class D implements I {
...
}
...
}
回答by Shawn
public interface A
{
public void helloWorld();
public static class B implements A{
@Override
public void helloWorld() {
System.out.print("Hello World");
}
}
}
回答by Foo Bah
The Java rule is that only one public class or interface can show up in a source file, and the name must match the file (i.e. Test.java --> public class Test or public interface Test, but not both).
Java 规则是在源文件中只能出现一个公共类或接口,并且名称必须与文件匹配(即 Test.java --> 公共类 Test 或公共接口 Test,但不能同时出现)。
回答by Deepak
One also needs to understand interface driven programmingas next step while understanding an interface. It tell what is actual use of interface. What role it plays in a Java (or any other language) program.
在理解接口的同时,下一步还需要理解接口驱动编程。它告诉什么是接口的实际用途。它在 Java(或任何其他语言)程序中扮演什么角色。