Reputation: 163
What I want:
Instead of "Object" in "public void insertDog(Object object)" method, I would like a generic that extends the class extending the abstract class "DogKennel." For example, if I create a class called "RetrieverDogKennel" that extends "DogKennel," I would like the parameter in the "RetrieverDogKennel" class's "insertDog(...)" method to only accept "Retriever" Objects. Though it wouldn't look like this "insertDog(Retriever retriever)" the method would act like it, only allowing retriever objects in its parameter.
public abstract class DogKennel
{
public void insertDog(Object object)
{
//does something and the object is not stored
}
}
public class RetrieverDogKennel extends DogKennel
{
public <T extends Retriever> void insertDog(T object)
{
//does something and the object is not stored
}
}
If you try to put another dog breed into the RetrieverDogKennel, I want it to be an error.
LabradorDogKennel labradorDogKennel = new LabradorDogKennel();
RetrieverDogKennel retrieverDogKennel = new LabradorDogKennel();
Labrador bullet = new Labrador();
Retriever buster = new Retriever();
Retriever sparky = new Retriever();
//No Error
retrieverDogKennel.insertDog(buster);
//Error
retrieverDogKennel.insertDog(bullet);
Upvotes: 1
Views: 53
Reputation: 159165
UPDATED
You need to make both classes generic, not the subclass method:
public interface Dog {
}
public class Labrador implements Dog
{
}
public abstract class DogKennel<T extends Dog> {
public void insertDog(T dog) {
//does something and the dog is not stored
}
}
public final class RetrieverDogKennel extends DogKennel<Retriever> {
}
public final class GeneralDogKennel extends DogKennel<Dog> {
}
With that code the RetrieverDogKennel
class has an insertDog(Retriever dog)
method, with implementation inherited from the base class.
The GeneralDogKennel
class has an insertDog(Dog dog)
method, i.e. it will accept any type of dog.
Upvotes: 1