3

What does this exactly mean in Java?

Interface defines a contract for implementing classes

mssrivatsa
  • 343
  • 1
  • 3
  • 10
  • 3
    While your question is not a duplicate (at least, I cannot find exact duplicates), it was answered quite a lot of times here (check this wonderful [thread](http://stackoverflow.com/questions/219425/interface-contract-class-object?rq=1), for example). Why didn't you use search before asking? Perhaps you had, but have something missing from these explanations still? – raina77ow Aug 31 '12 at 14:02
  • The terminology probably stems from the legal profession, in which a contract mandates what another entity will adhere to. – Duncan Jones Aug 31 '12 at 14:02
  • An interface defines what implementing classes must implement. ;) – Peter Lawrey Aug 31 '12 at 14:04
  • @raina77ow I did search for it(not a rigorous one though). Thanks for your reply. I put this up because I didn't quite understand what this statement exactly meant from my search. – mssrivatsa Aug 31 '12 at 14:22

2 Answers2

8

It means that by implementing an interface, the class agrees to implement all of the functionality specified by the interface.

Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
  • 1
    Simply put, if a class does not implement all of the methods of its interfaces, the program will refuse to compile. –  Aug 31 '12 at 14:01
  • And it means that you can use an object of this class everywhere where an object providing the functionality specified by the interface is needed. – JohnB Aug 31 '12 at 14:02
0

In interface you simply declare the members(say methods). For example

public Interface Product{

protected void getProduct();
protected void getProductId();
}

Whereas in a class you can implement the above interface and can define these methods...

public class ProductClass implements Product{

protected void getProduct()
{
    System.out.println("Product is: ");
}
protected void getProductId()
{
    System.out.println("Product Id is: ");
}
}

So you can see the methods declared in interface are defined in the class. Basically, you can say that interface just provides the blueprint but class actually does the whole work.

Kabir Prince
  • 25
  • 2
  • 6