-1

i have searched a lot but did not get exact answer for this Question hope i will get it from here. what is exactly the use of referring object of a class to an interface instead of referring to the same class ??

void foo(list l){}

public static void main(String a[]){
List l = new ArrayList(); // why use this?
ArrayList a = new ArrayList(); //instead of this?
foo(l);
foo(a);

}
Deepak Odedara
  • 481
  • 1
  • 3
  • 12
  • 4
    This is answered all over the internet *and* Stack Overflow. Google for "code to interface not implementation" or any of several other similar queries. – Dave Newton Jun 19 '13 at 13:46
  • 1
    Your question is pretty unclear, but I suspect you want http://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface – Jon Skeet Jun 19 '13 at 13:46
  • 1
    Look here: http://stackoverflow.com/q/383947/2030471 –  Jun 19 '13 at 13:46

2 Answers2

1

Maybe because an interface is something like a contract, which can be fullfilled by an implementation. You shouldn't depend on an implementation, because its about to change constantly, instead an interface/contract should not. Referring to an interface makes your implementation more robust.

1

Sometimes, the actual class of an instance does not matter, but only the interface it implements.

Also sometimes, it is impossible to know the actual class of an instance in compile time, but we only know the interface this class will implement.

For example, you have an interface called GeometricFigure

public static interface GeometricFigure {
    public Double getGirth();
    public String getName();
}

And you use this interface in a real class, for example, Canvas. Canvas has a list of GeometricFigures.

public class Canvas {
    private List<GeometricFigure> figures;

    public void printAllFigures() {
         for (GeometricFigure figure : figures) {
              System.out.println(figure.getName() + " " + figure.getGirth());
         }
    }
}

Now, your Canvas is independent of actual implementations of GeometricFigure. Canvas does not care how you is GeometricFigure is implemented, is it a square, circle or whatever. It only that this class can return a name and a girth so it can print them. So, the actual implementations can be Square, Circle, Triangle, etc. Only important thing is that these future classes implement the GemometricFigure interface.

For example:

public class Square implements GeometricFigure {

    private String name;
    private Double sideLength; 

    public Square(String name, Double sideLength) {
        this.name = name;
        this.sideLength = sideLength;
    }        

    @Override
    public Double getGirth() {
        return 4 * sideLength;
    }

    @Override
    public String getName() {
        return name;
    }
}
darijan
  • 9,725
  • 25
  • 38