What are the benefits of Creating interface with Java?

+1 Amish Garg · January 2, 2015
What are the benefits of Creating interface with Java?Can u give some examples...?

Post a Reply


Oldest  Newest  Rating
0 Branislav Lazic · January 4, 2015
This is a really good question! In "Head first Java" as S.F. wrote, I found it quite poorly explained.  
Let's start from rough definition of interface which is something like this: Interface is an abstract class that contains only abstract method. Interface describes what your code should do while implementation class does what's described in interface. But sometimes, interface in just about contract and it doesn't have to necessarily have any abstract method. How? 

Let's see it in next example:

Let's say that we have data access layer in some application. I.e. let's use standard DAO pattern. And let's define interface without of any abstract method called Entity:

public interface Entity {


Now let's create some entity class, like Student, which state can be persisted, deleted, updated... in database:

public class Student implements Entity {

  private int id;
  private String name;
  private int age;
  // Getters and setters


Now, we will create interfaces that describe what implementation classes can do. I.e. if Student can be deleted from database, we will create DeletableDAO interface:

public interface DeletableDAO<E extends Entity> {

  void delete(E e);

But you will also notice that DeletableDAO is a generic class (interface) with one type parameter. 
And our implementation class will look something like this:

public class StudentDAOImpl implements DeletableDAO<Student> {

  public void delete(Student s) {
    //Do stuff


What this actually mean?
It means if our implementation class implements this interface, we will be able only to delete entity that implements Entity interface. Which further means that Entity interface is there purely because of contract! It doesn't have any abstract method that will describe what our implementation class (Student in our case) will do. It's just there to protect our DAO layer from passing of undesirable entities. You cannot pass entity class as a type argument if it doesn't implement Entity interface.
0 Bacon+Tuna S · January 2, 2015
  • 1

Java / Android Development


Very popular language used to create desktop applications, website applets, and Android apps.

Bucky Roberts Administrator