Reputation: 28555
I wasn't sure how to properly name this question, so if its better suited to be edited, please do so. My question has to do with using generic types in an interface and then forcing the implementation into a specific type. Something like this:
public interface Test<T> {
void testMethod(Object<T> obj);
}
And then instead of allowing a generic object in an implementation of this interface, set the type somehow.
public class TestImpl implements Test<TestObject1> {
@Override
public void testMethod(TestObject1 obj) {
//Do something
}
}
public class Test2Impl implements Test<TestObject2> {
@Override
public void testMethod(TestObject2 obj) {
//Do something
}
}
Except you cannot paramaterize Object and i'm not sure how to set this sort of thing up. Is it even possible? Right now I just use generic Object, but that leaves me being forced to check the type of class being passed in for every single method and/or casting etc etc. It would be so much cleaner if I could just use generics on the interface and then specific classes on the implementation.
Upvotes: 1
Views: 466
Reputation: 76908
public interface Test<T> {
void testMethod(T obj);
}
You were close.
Then you can either write your classes the way you have them if testMethod
is specific to the Class being passed in, or ...
public class TestImpl<T> implements Test<T> {
@Override
public void testMethod(T obj) {
//Do something
}
}
Now you can instantiate your class via new TestImpl<TestObject>()
or new TestImpl<TestObject2>()
Upvotes: 4