当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Why should we declare an interface inside a class?

问题描述:

Why should we declare an interface inside a class in Java?

For example:

public class GenericModelLinker implements IModelLinker {

private static final Logger LOG =LoggerFactory.getLogger(GenericModelLinker.class);

private String joinAsPropertyField;

private boolean joinAsListEntry;

private boolean clearList;

private List<Link> joins;

//instead of a scalar property

private String uniqueProperty;

public interface Link {

Object getProperty(IAdaptable n);

void setProperty(IAdaptable n, Object value);

}

}

网友答案:

When you want to gather some fields in an object in order to emphasis a concept, you could either create an external class, or an internal (called either nested (static ones) or inner).

If you want to emphasis the fact that this cooperative class makes strictly no sense (no use) outside the original object use, you could make it nested/inner.

Thus, when dealing with some hierarchy, you can describe a "nested" interface, which will be implemented by the wrapping class's subclasses.

In JDK, the most significant example would be Map.Entry inner interface, defined within Map interface and implemented by various ways by HashMap, LinkedHashMap etc...

And of course, Map.Entry needed to be declared as public in order to be accessible while iterating the map wherever the code is.

网友答案:

If the interface definition is small and the interface will only be used by clients of the class it's defined in, it's a good way to organize the code. Otherwise, the interface should be defined in its own file.

网友答案:

This is inner interface. Java programming language allows defining inner classes and interfaces. This is typically useful if you want to limit visibility of this class or interface by scope of current outer class.

Some people use this mechanism for creating a kind of namespace. IMHO this is abuse of the language feature (in most cases).

网友答案:

To encapsulate behavior in a generic and resuable way.

Apart from nice example of Map.Entry used by Map implementation classes another good example is implementation of Strategy Pattern, where a execution strategy is evaluated and applied internally.

class Test
{

..
interface Cipher {
 doAction();
}
class RAMPCipher implements Cipher{}
class DiskCipher implements Cipher{}
..
}
网友答案:

Inside your class you may need multiple implementations of an interface, which is only relevant to this particular class. In that case make it an inner interface, rather than a public / package-private one.
Only an interface inside a class can be declared private or protected. Sometimes, that makes sense, when the interface is only appropriate for use inside the outer class (or its subclasses).

分享给朋友:
您可能感兴趣的文章:
随机阅读: