Why do we need interfaces in Java
In this blog, we are going to know about the interfaces and its need in Java. Unlike C++, Java does not enable multiple inheritance. This means you can derive a subclass from more than one direct superclass. Multiple inheritance does have a purpose, though. Java accomplishes this by allowing you to “implement” several interfaces (but you can only “extends” from a single superclass).
An interface establishes a contract (or a protocol, or a shared understanding) regarding the capabilities of the classes.
- Every abstract method declared in an interface will have implementation when a class complies with the interface’s requirements.
- Interface identifies a collection of typical actions. These behaviors are accepted by the classes that implement the interface, and they offer their own implementation of the behaviors.
- As opposed to the real implementation, this enables you to programme at the interface. An interface’s primary function is to establish a communication contract between two objects.
- Knowing a class implements an interface means you can be sure it has concrete implementations of the methods declared in the interface and that you can safely call those methods.
- In other words, rather than relying on their individual implementation, two objects can communicate based on the contract stated in the interface.
- You can derive a subclass from more than one direct superclass thanks to multiple inheritance. If two direct superclasses have incompatible implementations, this presents a challenge. (Which subclass member should come next?) Multiple inheritance does have a purpose, though.
- Java accomplishes this by allowing you to “implement” several interfaces (but you can only “extends” from a single superclass). There can never be a conflict between the various interfaces because interfaces simply include abstract methods and do not actually implement them. (Interface can store constants, although doing so is not advised.
- A compilation fault will be indicated by the compiler if a subclass implements two interfaces with incompatible constants.)
- For example, the items that may be compared can be found pretty much anywhere in the object hierarchy; they do not need to share a common ancestor.
- Strings, Integers, and even your own Frames can be compared (say, a frame is “less” than another frame if it is more in the foreground - i.e. if it would overlay the other frame). Thus, if you wish to refer to anything that can be compared, you must define a variable with the most broad ancestor - in this example, Object. This is overly broad, as it may get values that are not comparable (and would throw errors when you try to compare them).
Thus, the interface Comparable: it picks all classes that provide comparison capabilities throughout the subclass-superclass tree.