Не понимаю почему не передаються аргументы в List
Должен написать класс House, который имеет поле residents типа List, и метод enter(Object resident). Также есть 4 класса: Dog, Puppy (extends Dog), Cat, Kitty (extends Cat). И суть в том, что метод enter() должен добавлять в класс House животных, но так чтобы если первый элемент при добавлении была кошка, могли добавляться только кошки, соответствующая ситуация с собаками.
Вот так выглядит метод Main.
public class Main {
public static void main(String[] args) {
Dog rex = new Dog("Rax");
Puppy randy = new Puppy("Randy");
Cat barbos = new Cat("Barbos");
Kitten murzik = new Kitten("Murzik");
House dogHouse = new House();
dogHouse.enter(rex);
dogHouse.enter(randy);
dogHouse.enter(murzik); //This must fail on compilation stage if you parameterize the dogHouse. Delete the line when solution is ready
System.out.println(dogHouse);
House catHouse = new House();
catHouse.enter(barbos);
catHouse.enter(murzik);
catHouse.enter(rex); //This must fail on compilation stage if you parameterize the catHouse. Delete the line when solution is ready
System.out.println(catHouse);
}
}
Только начинаю учить дженерики и пробовал такой способ но выдает ошибку, незнаю что делать.
public class House <T> {
private final List <? extends T> residents = new ArrayList<>();
public <T> void enter(T resident) {
residents.add(resident);
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("There are following residents in the house:\n");
for (Object resident : residents) {
builder.append(resident.toString()).append("\n");
}
return builder.toString();
}
}