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); } }
Yes, you can define an interface inside a class and it is known as a nested interface. You can't access a nested interface directly; you need to access (implement) the nested interface using the inner class or by using the name of the class holding this nested interface.
Why do we use an Interface? It is used to achieve total abstraction. Since java does not support multiple inheritances in the case of class, by using an interface it can achieve multiple inheritances. It is also used to achieve loose coupling.
In Java, an interface specifies the behavior of a class by providing an abstract type. As one of Java's core concepts, abstraction, polymorphism, and multiple inheritance are supported through this technology. Interfaces are used in Java to achieve abstraction.
An interface can be used to define a contract behavior and it can also act as a contract between two systems to interact while an abstract class is mainly used to define default behavior for subclasses, it means that all child classes should have performed the same functionality.
When you want to gather some fields in an object in order to emphasize a concept, you could either create an external class, or an internal (called either nested (static ones) or inner).
If you want to emphasize the fact that this cooperative class makes strictly no sense (has 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 the 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With