An interface defines a service contract. In simple terms, it defines what can you do with a class.
For example, let's use a simple interface called ICount
. It defines a count method, so every class implementing it will have to provide an implementation.
public interface ICount {
public int count();
}
Any class implementing ICount
, should override the method and give it a behaviour:
public class Counter1 implements ICount {
//Fields, Getters, Setters
@Overide
public int count() {
//I don't wanna count, so I return 4.
return 4;
}
}
On the other hand, Counter2
has a different oppinion of what should count
do:
public class Counter2 implements ICount {
int counter; //Default initialization to 0
//Fields, Getters, Setters
@Overide
public int count() {
return ++count;
}
}
Now, you have two classes implementing the same interface, so, how do you treat them equally? Simple, by using the first common class/interface they share: ICount
.
ICount count1 = new Counter1();
ICount count2 = new Counter2();
List<ICount> counterList = new ArrayList<ICount>();
counterList.add(count1);
counterList.add(count2);
Or, if you want to save some lines of code:
List<ICount> counterList = new ArrayList<ICount>();
counterList.add(new Counter1());
counterList.add(new Counter2());
Now, counterList
contains two objects of different type but with the same interface in common(ICounter
) in a list containing objects that implement that interface. You can iterave over them and invoke the method count
. Counter1
will return 0
while Counter2
will return a result based on how many times did you invoke count
:
for(ICount current : counterList)
System.out.println(current.count());