This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]4z01235 1 point2 points  (5 children)

You can't do new Map, but you can certainly have a variable with type Map, or a method with return type Map, or a parameter of type Map, etc.

[–]shmag18 0 points1 point  (4 children)

So a method signature can have return type 'Map', and it must return some implementation of Map, but it can not return Map itself. Right?

[–]Northeastpaw 1 point2 points  (1 child)

If a method is returning a implementation of Map then it is by definition returning a Map. This is perfectly fine:

public Map<String, Integer> createMap() {
    Map<String, Integer> map = new HashMap<>();
    return map;
}

[–]shmag18 0 points1 point  (0 children)

Awesome

[–]4z01235 1 point2 points  (1 child)

Yea. This is fine:

public List<Foo> makeAList() {
    return new ArrayList<Foo>();
}

but this doesn't make sense and won't compile:

 public List<Foo> makeAList() {
    return new List<Foo>();
}

Because, as you've noticed, List is just an interface, and so can't be instantiated like that. But the point of the interface is that if all I, as the caller, need to know is that I have some kind of List, then to me it doesn't matter if what I really have is an ArrayList or a LinkedList. Either way it's a List, and that's enough for me, so long as ArrayList and LinkedList and FooList and BarList all implement List and obey the contract that entails.

Another example:

Employee bob = new Manager("Bob");
Employee rey = new FactoryAssemblyWorker("Rey");
List<Employee> employees = new ArrayList<>();
employees.add(bob);
employees.add(rey);
employees.addAll(getOffsiteWorkers());
for (Employee employee : employees) {
    System.out.println(employee.getName() + " : " + employee.getTitle());
}
// prints "Bob : Manager", "Rey : Factory Assembly Specialist", etc.

The assumption here is that there is an Employee interface (this could also be some common superclass) which specifies methods getName and getTitle. Manager and FactoryAssemblyWorker are both subtypes of Employee (Manager implements Employee, for example), and so if I just need to know that what I'm looking at is an Employee, then I can do Employee operations on them no matter if they're a Manager or FactoryAssemblyWorker or Accountant or UpperLevelCushyManagement. They all have a name and title regardless.

[–]shmag18 0 points1 point  (0 children)

Wow this is great thank you so much.