I have two programs.
First one is without ‘Buffer’ interface and second is with ‘Buffer’ interface.
Both programs give me same output.
My question is.
why I need to create “Buffer” interface while I can get same output without interface?
Here is my both programs:
Without Interface:
public class MainClass {
public static class producer {
maintainBuffer bf;
producer(maintainBuffer buffer) {
this.bf = buffer;
}
public void setData() {
for (int i = 0; i <= 10; i++) {
bf.set(i);
}
}
}
public static class reader {
maintainBuffer bf;
reader(maintainBuffer buffer) {
this.bf = buffer;
}
public void getData() {
System.out.println("From Reader Class:-" + bf.get());
}
public void extraData() {
System.out.println("Extra DATA");
}
}
public static class maintainBuffer {
int buffer = -1;
public int get() {
return buffer;
}
public void set(int a) {
buffer += a;
}
}
public static void main(String str[]) {
maintainBuffer b = new maintainBuffer();
producer p = new producer(b);
p.setData();
reader r = new reader(b);
r.getData();
r.extraData();
}
}
With Interface
public class MainClass {
public static class producer {
Buffer bf;
producer(Buffer buffer) {
this.bf = buffer;
}
public void setData() {
for (int i = 0; i <= 10; i++) {
bf.set(i);
}
}
}
public static class reader {
Buffer bf;
reader(Buffer buffer) {
this.bf = buffer;
}
public void getData() {
System.out.println("From Reader Class:-" + bf.get());
}
public void extraData() {
System.out.println("Extra DATA");
}
}
public static interface Buffer{
public int get();
public void set(int a);
}
static class maintainBuffer implements Buffer{
int buffer=-1;
public int get() {
return buffer;
}
public void set(int a) {
buffer +=a;
}
}
public static void main(String str[]) {
Buffer b = new maintainBuffer();
producer p = new producer(b);
p.setData();
reader r = new reader(b);
r.getData();
r.extraData();
}
}
With an interface you can use other implementations later without changing all your code. E.g. if you use a List interface, this could be a LinkedList, an ArrayList, a CopyOnWriteArrayList or something else.
You are making it clear, the details of the implementation are not important.
On the other hand, I wouldn’t go around making an interface for every class. In most cases adding an interface later in the unlikely event you really need it isn’t always a difficult one.
I would use an interface when you are want loose coupling e.g. when the caller is another module or used by another developer. If you have tight coupling like a package local implementation, I might not bother with an interface.
In the above example, you might want to add a unit test to see what values are set or a developer might want to use a Buffer which logs which values are set. Using an interface makes this easier.