Search code examples
javaimplements

How are Java interfaces used?


I'm a beginner Java programmer and have been experiencing difficulty grasping what the big picture of implementation is in OOP in the Java language.

I will try to frame my question with the pseudocode below (apologies if it is not that pretty):

interface{
  foo();
}

class a {
  //stuff
  foo() OPERATIONS;
}
class b {
  //stuff
  foo() OPERATIONS;
}

//The OPERATIONS segment is actually the *work* the foo does: i.e., if foo were 
//print, it would be the System.out.println("");

Now, what is the purpose of an interface, if it is within the actual classes that the interface's 'foo' OPERATIONS are declared? I thought the purpose of an interface was to create, if you will, a 'method grab bag' that is outside of all of the class obfuscation to keep from having to restructure the hierarchy that could be modified in one portion of code and apply to many implementing classes. In other words, I imagined an interface would be like what a function would be used for in 'C' language: a sequestered and concise set of operations clustered together and encapsulated to be called on when needed, and grouped in a code segment so that one could modify the OPERATIONS of foo within the interface and it apply to ALL classes implementing the interface. What am I missing?

Thanks!


Solution

  • Interface in java is like a contract with the implementing class. When you implement an interface you have to make sure that either you implement all the methods in the interface or make your class abstract. Lets take a real like analogy.

    You are creating a Car. Now as you know there can be a number of cars out there i.e. Mercedes, BMW, Audi and so on. You want to make sure that each Car should contain changeGear(), hasWheels(), hasDoors() methods in them, so how would you force this criteria on all possible cars. Simply create an interface named Car that has all these methods in it like

    public interface Car{
    boolean changeGear();
    boolean hasWheels();
    boolean hasDoors();
    }
    

    Now every class that implements this interface has to implement all these methods. So, in future if you create a Ferrari class implementing Car interface it has to abide by this contract.

    Edit: A thing to note here is that all the classes that implement the interface are not restricted to use only the methods from the interface. It is just like the implementing class has to make sure that it at least implements the methods from interface. Like in our example Ferrari class can very well implement the isSportCar() method which is only contained in Ferrari class.