0

While going through some lecture video on interface. I noticed

If we don't know about implementation, just requirement specification then go for interface.

What can be the scenario? Though I've used interface in many cases, but didn't gwt the essence of interface, as stated.

  • 1
    Please link to the video if possible to provide some context. – null Jul 25 '18 at 15:49
  • Interfaces are integral parts of several important patterns, such as IOC and Onion. And as a side note, they also let you control what gets exposed via the interface. – RandomUs1r Jul 25 '18 at 17:10
  • 1
    Possible duplicate of Why are interfaces useful? – e_i_pi Jul 25 '18 at 20:37
7

If we don't know about [the] implementation, just the requirement specification, then go for interface.

What that means is that you can sketch out an architecture by designing and writing the interfaces first, and defer writing the implementations that satisfy those interfaces to a later time.

Let's say you're one of the designers of the Java development environment. You want to provide a sort function for your collections. But you don't know how to sort custom types (i.e. user-defined classes) because you don't know how to determine whether one object of a given class is greater than another. You can't write an implementation for that comparison, because you don't know how to do that for any given class that someone may write.

So you provide an interface called Comparable. It defines a method

int compare<T>(T other)

that takes as a parameter an "other" object of the specified type, and returns a number that tells Java whether the other object is equal, greater than or less than this object. Now you can let people derive their class from your interface and write a Compare method implementation. Your sort function now understands how to sort these objects because it understands Comparable and can call their Compare method to compare two instances of their objects.

  • Can i get the notions from the code sir, it would be a bit easier for me to understand. Although I've got the notions of your words. As a beginner i might have some technical difficulties to understand. Please keep in touch sir!! – Surya Bhusal Jul 26 '18 at 17:10
1

The essence of an Interface is a contract.

I don't care how the result is achieved, just that

  • The function exists
  • It has return type X
  • It has parameters Y

If I do care about the implementation, then I would use a base class or abstract class, allowing me to specify some of the code to be run by all child classes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.