是否可以在 java 的接口内部有一个内部类???
7 回答
You can. But here's what O'Reilly says about it:
Nested Classes in Interfaces?
Java supports the concept of nested classes in interfaces. The syntax and dynamics work just like nested classes declared in a class. However, declaring a class nested inside an interface would be extremely bad programming. An interface is an abstraction of a concept, not an implementation of one. Therefore, implementation details should be left out of interfaces. Remember, just because you can cut off your hand with a saw doesn't mean that it's a particularly good idea.
That said, I could see an argument for a static utility class nested into an interface. Though why it would need to be nested into the interface instead of being a stand-alone class is completely subjective.
我同意这通常很少见,但是当接口方法需要返回多条信息时,我确实喜欢在接口中使用内部类来提供服务,因为它实际上是合同的一部分,而不是实现的一部分。例如:
public interface ComplexOperationService {
ComplexOperationResponse doComplexOperation( String param1, Object param2 );
public static class ComplexOperationResponse {
public int completionCode;
public String completionMessage;
public List<Object> data;
// Or use private members & getters if you like...
}
}
显然,这也可以在一个单独的类中完成,但对我来说,感觉就像我将接口定义的整个 API 保持在一个位置,而不是分散开来。
Yes, it is possible but it is not common practice.
interface Test
{
class Inner
{ }
}
class TestImpl implements Test
{
public static void main(String[] arg)
{
Inner inner = new Inner();
}
}
不直接回答您的问题,但在相关说明中,您还可以将一个接口嵌套在另一个接口中。这是可以接受的,特别是如果您想提供意见。Java 的集合类执行此操作,例如Map.java
在Map.Entry
视图的情况下:
public interface Map<K,V> {
...
public static interface Entry<K,V> {
....
}
}
这是可以接受的,因为您没有将实现细节混合到您的界面中。您只是在指定另一个合同。
Yes. Straight from the language spec:
An inner class is a nested class that is not explicitly or implicitly declared
static
.
And (boldface mine):
A nested class is any class whose declaration occurs within the body of another class or interface.
这是合法的,但我只使用嵌套接口(如前所述)或嵌套枚举。例如:
public interface MyInterface {
public enum Type { ONE, TWO, THREE }
public Type getType();
public enum Status { GOOD, BAD, UNKNOWN }
public Status getStatus();
}
我发现一个非常有用的用例是,如果您有一个创建接口实例的构建器。如果构建器是接口的静态成员,您可以像这样创建一个实例:
DigitalObject o = new DigitalObject.Builder(content).title(name).build();