What are the benefits of Creating interface with Java?Can u give some examples...?
What are the benefits of Creating interface with Java?
Post a Reply
|Oldest Newest Rating|
· January 2, 2015
· 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:
Now let's create some entity class, like Student, which state can be persisted, deleted, updated... in database:
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:
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:
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.
Java / Android Development
Very popular language used to create desktop applications, website applets, and Android apps.
|Bucky Roberts Administrator|