Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should we refer to an object by the type of the interface? [duplicate]

Tags:

java

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?

like image 724
Ronald Avatar asked Jun 08 '15 07:06

Ronald


2 Answers

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.

like image 134
Eran Avatar answered Oct 11 '22 03:10

Eran


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.

like image 32
Sylvia Stuurman Avatar answered Oct 11 '22 03:10

Sylvia Stuurman