I have this method in my interface:
public String getValue();
String is just for the example here, I don't want to return a String.
And I want to put the method in classes that will return ints, chars or bools (depending on the class). For example, I have a class Animal that implements my interface and has this method. I want it to return an int when this method is invoked in an animal. I have another class person that has this method, and when this method is invoked on a Person I want it to return a char.
public class Animal implements myInterface {
@Override
public int getValue() {
return 5;
}
}
public class Person implements myInterface {
@Override
public char getValue() {
return 'c';
}
}
I understand I have to do this with generics. But how exactly do I do it?
If I replace String in the interface with a generic type, like:
public <T> T getValue();
then it says I cannot cast from int (or char) to T.
What should I do? Thanks.
The proper way to do that is by having a generic interface:
public interface MyInterface<T> {
public T getValue();
}
public class Animal implements MyInterface<Integer> {
@Override
public Integer getValue() {
return 5;
}
}
However, this really reeks like an X/Y problem; not to mention that it's highly inefficient, boxing and unboxing all those primitives.
What are you trying to achieve? What is your goal?
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments