0

I am now studying JAVA. When we make interface like this, sometimes we create object like this

Sample code :-

interface test01{
    public boolean A(int i);
    public int B(int a);
    public String C (String c);
}


class ttt implements test01{

    public boolean A(int a){
        return true;
    }

    public int B(int a){
        return a;
    }

    public String C(String c){

        return c;
    }

}

public class Interface_test {

    public static void main(String[] args) {
        ttt t1 = new ttt();
        System.out.println(t1.A(1));
        System.out.println(t1.B(1));
        System.out.println(t1.C("C"));

        test01 tt = new ttt();
        System.out.println(tt.A(1));
        System.out.println(tt.B(1));
        System.out.println(tt.C("C"));

    }

}

This code's result is same but I was wondering why we use the pattern like this

"test01 tt = new ttt();"

instead of

"ttt t1 = new ttt();"

Please let me know...

Thank you!

Prasad
  • 1,562
  • 5
  • 26
  • 40
  • Refer this link : [Interface as a type in Java?](http://stackoverflow.com/questions/7275844/interface-as-a-type-in-java) – Rohit Gulati Jan 17 '17 at 13:44
  • They just want to explain that you can use the reference to the interface or the implementation of the interface, but you always have to create the instance of one implementation not the Interface. – cralfaro Jan 17 '17 at 13:45
  • 1
    The point that is maybe not 100% clear from the above DUP: you simply want to **reduce** the knowledge that your code has about anything. Example: there is the java.util.Set **interface** describing the base behavior of sets. Then there are various classes implementing that interface. And 99% of the time, **after** some set object was created, you do not care what kind of **underlying** class is actually used. The only thing that you **want** to **rely** on is: it is some object implement the Set interface! – GhostCat Jan 17 '17 at 13:47

1 Answers1

0

Interfaces are used as types to allow implementations to be swapped in the future without having to worry about changing method signatures or implementations in other classes that are using your interface.

If you didn't use an interface, you had to revisit all classes using your old implementation and change it to use the new implementation.

Interfaces are also used as an abstraction to hide logic of the implementing class from users of the interface.

Luciano van der Veekens
  • 6,307
  • 4
  • 26
  • 30