Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementation of generic interface with specific type in Java

Tags:

java

generics

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 (e.g., 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?

like image 565
flow2k Avatar asked Sep 01 '25 01:09

flow2k


1 Answers

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>.

like image 117
Eran Avatar answered Sep 02 '25 16:09

Eran