1

I've got the following (simplified) class definitions in my Java application:

public class Branch {
int branch_id;
String branch_name;

public Branch(int id, String name)
{
    branch_id = id;
    branch_name = name;
}
}

and:

public class BranchWithFleet extends Branch {

public Map<VanType, Integer> fleet;

public BranchWithFleet(int id, String name)
{
    super(id, name);

    fleet = new HashMap<VanType, Integer>();
}

I've written a routine to find "bad routes" whose arguments are based on the parent class (Branch) as it doesn't need any of the extra Fleet information, and has this general structure:

public void findBadRoutes(Map<Integer, Branch> branches, Integer rId)
{
    if (!(branches.containsKey(rId)))
    {
        // bad
    }
}

My question is as follows: if I am of the correct understanding that every BranchWithFleet is also a Branch, then why doesn't the following work?

Map<Integer, BranchWithFleet> branches = new HashMap<Integer, BranchWithFleet>();

Integer rId = 3;
findBadRoutes(branches, rId);

It fails with the following error in Eclipse's code-checking lint:

The method findBadRoutes(Map<Integer,Branch>, Integer) in the type [Type] is not applicable for the arguments (Map<Integer,BranchWithFleet>, Integer)

Surely a Map involving BranchWithFleet should be recognised as being one also identifiable with Branch?

EDIT: Foo(List<? extends Branch>) for the win: linked question

  • 2
    *" if I am of the correct understanding that every BranchWithFleet is also a Branch, then why doesn't the following work"* You are, but `List` is not also a `List`. See the linked question's answers for details, but the short version is that a `List` can't be a `List` because you can add a `Branch` to `List`, but you can't add a `Branch` to a `List` – T.J. Crowder Feb 24 '20 at 11:58
  • (And you're not alone with having gone down this line of reasoning. :-) ) – T.J. Crowder Feb 24 '20 at 12:02
  • 1
    You should read this answer : https://stackoverflow.com/questions/49736035/getting-incompatible-error-for-parent-child-classes-java – paroxit Feb 24 '20 at 12:07
  • Many thanks to both, extends Branch> was the answer I was looking for, and I understand the logic of that answer - I just had trouble finding it! – Adam Gripton Feb 24 '20 at 12:39

0 Answers0