somnathchakrabarti
somnathchakrabarti

Reputation: 3086

How to extend a generic class with bounded typed parameter

I am trying to extend a Generic class with bounded typed parameter with another generic class with typed parameter which follows the super generic's typed parameter.

Super Generic with upper bounded type parameter

public abstract class Cage<T extends Animal> { 
    protected Set<T> cage = new HashSet<T>();
    public abstract void add(T animal);
    public void showAnimals() {
        System.out.println(cage);
    }
}

Generic class I want to create with a specific bounded type e.g. Lion

I tried the below code but I am getting an error The type parameter Lion is hiding the type Lion and Syntax error on token "extends", , expected

For the add() method in LionCage class I am getting the error The method add(Lion) of type LionCage must override or implement a supertype method

LionCage class meant for Cage<Lion extends Animal>

public class LionCage<Lion extends Animal> extends Cage<T extends Animal> {
    @Override
    public void add(Lion l) {
        cage.add(l);

    }
}

My Animal class with its subclasses Lion, Rat, etc are defined in Animal.java

public class Animal {
    public String toString() {
        return getClass().getSimpleName();
    }   

}

class Rat extends Animal {}
class Lion extends Animal {}

Since I am getting the errors, I am guessing that the approach I am following may not be correct. In that case, is there any standard way of implementing this scenario in Java generics?

Upvotes: 1

Views: 1246

Answers (1)

ernest_k
ernest_k

Reputation: 45309

Your LionCage class doesn't have to be generic, but it has to pass a concrete type paramter (Lion) in the extends clause:

public class LionCage extends Cage<Lion> {
    @Override
    public void add(Lion l) {
        cage.add(l);

    }
}

Upvotes: 6

Related Questions