2

I tried to understand the use of interface and read this article which says:

Interfaces define a standardized set of commands that a class will obey.

The commands are a set of methods that a class implements.

The interface definition states the names of the methods and their return types and argument signatures. There is no executable body for any method that is left to each class that implements the interface.

I would like to ask why do I need to state name of methods and their return types and argument signatures in an interface while I can implement them directly in a class?

Aan
  • 12,247
  • 36
  • 89
  • 150
  • 1
    in that way you don't marry with no one implementation, only with a contract – nachokk Sep 02 '13 at 21:30
  • Start [here](http://docs.oracle.com/javase/tutorial/java/concepts/interface.html), and you'll probably land [here](http://docs.oracle.com/javase/tutorial/java/IandI/index.html). Voting to close though. – Mena Sep 02 '13 at 21:31

1 Answers1

2

In simplest way I would say the main use is polymorphism i.e, ability to perform the same operation on a number of different objects.

From here:-

An interface is a contract (or a protocol, or a common understanding) of what the classes can do. When a class implements a certain interface, it promises to provide implementation to all the abstract methods declared in the interface. Interface defines a set of common behaviors. The classes implement the interface agree to these behaviors and provide their own implementation to the behaviors. This allows you to program at the interface, instead of the actual implementation. One of the main usage of interface is provide a communication contract between two objects. If you know a class implements an interface, then you know that class contains concrete implementations of the methods declared in that interface, and you are guaranteed to be able 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.

Secondly, Java does not support multiple inheritance (whereas C++ does). Multiple inheritance permits you to derive a subclass from more than one direct superclass. This poses a problem if two direct superclasses have conflicting implementations. (Which one to follow in the subclass?). However, multiple inheritance does have its place. Java does this by permitting you to "implements" more than one interfaces (but you can only "extends" from a single superclass). Since interfaces contain only abstract methods without actual implementation, no conflict can arise among the multiple interfaces. (Interface can hold constants but is not recommended. If a subclass implements two interfaces with conflicting constants, the compiler will flag out a compilation error.)

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331