Skip to content
Advertisement

Is it possible to override an inherited method with type parameter List with List?

I’m having trouble changing the type parameter of an inherited method.

abstract class Animal {
    abstract List<Animal> animalList();
}

public class Dog extends Animal {
    @Override
    public List<Dog> animalList() {
        ...
        ...
    }
}

public class Cat extends Animal {
    @Override
    public List<Cat> animalList() {
        ...
        ...
    }
}

All animal subclasses need to implement a method animalList. What’s the best practice of doing this if i want the best possible code regarding readability and maintainability? Please note that this is extremely simplified i comparison to the actual project.

Advertisement

Answer

I don’t know what the best solution is, but I would do the following:

import java.util.List;
abstract class Animal {
    abstract <T extends Animal> List<T> animalList();
}

import java.util.List;
public class Dog extends Animal {
    @Override
    List<Dog> animalList() {
        return null;
    }
}

import java.util.List;
public class Cat extends Animal{
    @Override
    List<Cat> animalList() {
        return null;
    }
}
6 People found this is helpful
Advertisement