flow2k
flow2k

Reputation: 4347

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 (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?

Upvotes: 4

Views: 3676

Answers (2)

davidxxx
davidxxx

Reputation: 131324

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){...};
}

Upvotes: 3

Eran
Eran

Reputation: 393771

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

Upvotes: 6

Related Questions