Why are interfaces introduced in Java?

JavaObject Oriented ProgrammingProgramming

  • An interface is a contract of what the classes can do.
  • When a class implements an interface, it can provide implementation to all the abstract methods declared in the interface. An interface defines a set of common behaviors The classes implement the interface agrees to these behaviors and provide their own implementation to the behaviors.
  • One of the main usages of an interface is to provide a communication contract between two objects.
  • If we know a class implements an interface, then we know that class contains concrete implementations of the methods declared in that interface and we are guaranteed to invoke these methods safely. In other words, two objects can communicate based on the contract defined in the interface, instead of their specific implementation.
  • Java does not support multiple inheritances, Multiple inheritances permit us to derive a subclass from more than one direct superclass. This poses a problem if two direct superclasses have conflicting implementations. Java does this by permitting us to implements more than one interfaces.
  • Since interfaces contain only abstract methods without actual implementation, no conflict can arise among the multiple interfaces.
Published on 28-May-2019 15:14:48