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,6005 gold badges27 silver badges42 bronze badges
asked Jan 17, 2017 at 13:42
3
  • Refer this link : Interface as a type in Java? Commented Jan 17, 2017 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. Commented Jan 17, 2017 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! Commented Jan 17, 2017 at 13:47

1 Answer 1

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.

answered Jan 17, 2017 at 13:45
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.