Home  >  Article  >  Java  >  Why should interfaces be introduced in Java?

Why should interfaces be introduced in Java?

WBOY
WBOYforward
2023-09-21 11:01:171450browse

Why should interfaces be introduced in Java?

  • #An interface is a contract for the operations a class can perform.
  • When a class implements an interface, it can provide implementations for all abstract methods declared in the interface. An interface defines a common set of behaviors. Classes that implement the interface agree to these behaviors and provide their own implementations of them.
  • One of the main uses of interfaces is to provide a communication contract between two objects.
  • If we know that a class implements an interface, then we know that the class contains the declarations in the interface The specific implementation of the methods, and we can ensure that these methods are called safely. In other words, two objects can communicate based on the contract defined in the interface, rather than their concrete implementation.
  • Java does not support multiple inheritance, which allows us to directly derive subclasses from multiple superclasses. Problems can arise if the implementations of two immediate superclasses conflict. Java achieves this by allowing us to implement multiple interfaces.
  • Since the interface only contains abstract methods without actual implementation, there will be no conflicts between multiple interfaces.

The above is the detailed content of Why should interfaces be introduced in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete