4

In the following code, I have two different ways to instantiate an object of class B.

public interface A {}

public class B implements A {}

public static void main(String[] args)
{
    A test1 = new B();
    B test2 = new B();  
}

What is the difference between the variables test1 and test2?
When should I instantiate using the Interface type (type1) and when should I not?

almightyGOSU
  • 3,731
  • 6
  • 31
  • 41
Ronald
  • 2,721
  • 8
  • 33
  • 44
  • 1
    test1 is limited to the methods that are in the interface, test2 isn't. A lot of people write code to interfaces, simply because they don't want to wait with working until the other team has finished writing the implementations of that interface, or simply because they don't know what the implementations will be. – Stultuske Jun 08 '15 at 07:13
  • You should start with https://docs.oracle.com/javase/tutorial/java/concepts/inheritance.html and https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html - I'm not sure if you have already but that should give starting point. – Praba Jun 08 '15 at 07:14

3 Answers3

4

You use the type of the interface when you want to keep your code more flexible, as it allows you to change the implementation of interface A you are using by changing a single line of code. For example - A test1 = new C(); will switch your code from using the B implementation of A to using the C implementation of A. You should prefer using variables of the interface type whenever possible.

If you are using the type of a specific implementation, as in B test2 = new B();, you are tying your code to that specific implementation, and you can't switch to a different implementation as easily. Sometimes you can't avoid it if your code has to call methods of B that are not part of the interface A.

Eran
  • 387,369
  • 54
  • 702
  • 768
1

One of the golden rules of object oriented programming is Program to an interface, not to an implementation. By programming to an interface, you can easily add new classes implementing that interface. The only place where you will have to change your code is where such an object is created. You should isolate those places.

In your code, that means that you should isolate the place where you create your object. In every place where you use that object, you should refer to its type as interace A.

0

we required reference of interface A , when we have no idea about class where the interface was implemented , but in compile time case the both results same..

user4291121
  • 31
  • 1
  • 7