Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Why does some Java declaration have object reference not match the object type?

For the following code, why does the variable use Map declaration instead of HashMap declaration? Would it be wrong to have the variable reference also be HashMap?

Map<Integer, String> mapExample = new HashMap<Integer, String>();

Vs

Scanner input = new Scanner(System.in);

When declaring objects, when would it be beneficial to have the variable type be different from the object type?

2 Answers

Hi

You use the Map declaration because then you could use any subtype from Map. Maybe you want to change some stuff in the future.

Because I'm really bad at explaining, this link might help you

https://stackoverflow.com/questions/1348199/what-is-the-difference-between-the-hashmap-and-map-objects-in-java

scanner is a class and is used directly. map is an interface and is implemented with various classes, such as hashMap, treeMap, etc. the java docs list what classes can be used to implement the map interface.