0

Java Newbie here

New instances are stored in variables. However, I see sometimes, that the type of the variable is different from the reference type of the object.

Y y = new x

Why do programmers do this?

Jakub Biały
  • 391
  • 2
  • 16
Asker1234
  • 3
  • 1
  • https://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface?r=SearchResults&s=1|373.7118 – GriffeyDog Aug 05 '20 at 19:08
  • 1
    This Oracle Java tutorial on [Interfaces and Inheritance](https://docs.oracle.com/javase/tutorial/java/IandI/index.html) may help you. – Scratte Aug 05 '20 at 19:17

2 Answers2

0

Because sometimes you have common interface for different implementations. For example

List<String> exampleList = new ArrayList<>(); 

and the other one

List<String> exampleList = new LinkedList<>();

Interface List provide for us the same methods for this two implementations, but how this methods works depends on implementation. Welcome

merc-angel
  • 394
  • 1
  • 5
  • 13
0

Most time Y in your example is an interface so you can change later the Implementation without to change the rest of your application

Thomas
  • 1,058
  • 8
  • 15