简体   繁体   中英

How to have an object and its subclasses as a parameter of an object

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> List<? extends Animal> ?

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);
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM