i have a basic question but i don't know how to solve it. pls help me!
if i have a class Zoo
public class Zoo{
private Animal animal;
private Long age;
}
and Animal para is this:
public class Animal{
private String name;
}
but now i have a new class is: Dog class, extends animal
public class Dog extends Node{
private String dogClass;
}
I want to make the animal property in Zoo also accept Dog class parameters, what should I do?
Is there an elegant way to write it like List<? extends Animal> ?
CodePudding user response:
You don't need to change anything: as Dog extends Animal, it can be assign to field Zoo.animal. You can however add a method in Zoo to get animal as an instance of a specific class:
public <T extends Animal> T getAnimal(Class<T> animalClass) {
return animalClass.cast(animal);
}
Or, if you don't want it to throw an exception if the animal is not of the specified class:
public <T extends Animal> T getAnimal(Class<T> animalClass) {
if (!animalClass.isInstance(animal)) {
return null;
}
return animalClass.cast(animal);
}
CodePudding user response:
If I'm not mistaken, to do what you're asking, all you have to do is insert constructors in the parent and child classes and associate their values in this way:
public class Animal{
private String name;
public Animal(String name){
this.name = name;
}
}
public class Dog extends Animal{
private String dogClass;
public Dog(){
super(dogClass);
}
}
Also, if you already plan to never instantiate the Animal class directly, as it is a generic object, you could make it abstract.
