简体   繁体   中英

Implementation of generic interface with specific type in Java

Consider the following generic interface:

interface Petlover<T>{
    void train(T somePet);
}

I understand that it's possible to provide generic implementations to generic interfaces (eg, class MalePetLover<T> implements Petlover<T> ). But I am having trouble implementing the interface for a specific type only:

class Dogperson implements Petlover<T> {
    int age;

    void train(String someDog){...};
}

The compilation error is train(String) in Dogperson cannot implement train(T) in Petlover . What would be a right way to handle this?

Since you expect train to accept a String , your class should implement Petlover<String> :

class Dogperson implements Petlover<String> {
    int age;

    public void train(String someDog) {...};
}

or perhaps the train() method of Dogperson should accept a Dog argument, and then the class would implement Petlover<Dog> .

The subclass that extends a generics class has to conform to the type that it specifies in its own declaration.

You declare : class Dogperson implements Petlover<T> { , so the train() method has to have this signature : void train(T someDog){...};

If you want to have this signature in the subclass:

void train(String someDog){...};

you have to declare a subclass that implements PetLover by specifying the String class as parameterized type :

class Dogperson implements Petlover<String> {
     public void train(String someDog){...};
}

You can specify any parameter as T derives from Object in the interface.
For example, if you want to have a Dog as type used in the subclass, you could write it :

class Dogperson implements Petlover<Dog> {
     public void train(Dog dog){...};
}

For example, if you want to have a Cat, you could write it :

class Catperson implements Petlover<Cat> {
     public void train(Cat cat){...};
}

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