I have constructed a map and try to put subclasses of a given class into it. Problem is that map accepts some of them, but not all. Please let me know what is the problem, why some subclasses are not accepted and how to fix it. I also tried to make class Cat and Dog extend Rodent (since Hamster works here), but this doesn’t work. Thank you
Here is the code for each class:
package typeinfo.pets;
public class Pet extends Individual {
public Pet(String name) { super(name); }
public Pet() { super(); }
} ///:~
package typeinfo.pets;
public class Rodent extends Pet {
public Rodent(String name) { super(name); }
public Rodent() { super(); }
} ///:~
package typeinfo.pets;
public class Cat extends Pet {
public Cat(String name) { super(name); }
public Cat() { super(); }
} ///:~
package typeinfo.pets;
public class Hamster extends Rodent {
public Hamster(String name) { super(name); }
public Hamster() { super(); }
} ///:~
import typeinfo.pets.*;
import java.util.*;
import static net.mindview.util.Print.*;
public class PetMap {
public static void main(String[] args) {
Map<String,Pet> petMap = new HashMap<String,Pet>();
petMap.put("My Hamster", new Hamster("Bosco"));
//the two lines here cause problems "Map<String, Pet> is not
// applicable to <String, Cat>
petMap.put("My Cat", new Cat("Molly"));
petMap.put("My Dog", new Dog("Ginger"));
print(petMap);
Pet dog = petMap.get("My Dog");
print(dog);
print(petMap.containsKey("My Dog"));
print(petMap.containsValue(dog));
}
}
As most of the users suggested, your problem doesn’t lie in the inheritance tree, but somwhere along the lines of what classes you imported and from where.
The
CatandDogyou use in your main method may not be subclasses ofPet; probably that’s whyHamsteris accepted and the others aren’t. I tried to make your code running and added what was missing. The following, for example works:Please recheck your package definitions and imports.