Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are Java interfaces used? [closed]

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!

like image 478
Smith Will Suffice Avatar asked Feb 15 '23 01:02

Smith Will Suffice


1 Answers

An interface specifies a contract on what a class does, but not how it does it. Imagine a sort algorithm, there could be many implementations.

public interface Sorter {

    void sort(List<String> list);

}

You could use a bubble sort, a merge sort, quick sort, etc

But as a user of the sorter, I may not care.

class SortClient {

    SortClient(Sorter sorter, List<String> list) {
      sorter.sort(list);
    }

}

The SortClient doesn't care how you sort, just that it gets sorted.

In frameworks that do dependency injection such as Spring or Guice, this becomes very important. These frameworks allow you to configure which implementation is used without changing the user of it.

Interfaces have other practical uses. They are useful for creating mocks/stubs for testing. In the SortClient case above, maybe you want to create some stub for the sorter, such as:

ExceptionThrowingStubSortClient implements Sorter {
   void sort(List<String> list) {
      throw new SortException("Testing the exception handling");
   }
}
like image 60
Jeff Storey Avatar answered Feb 17 '23 20:02

Jeff Storey