简体   繁体   中英

Generic Types in Interface and Non Generic in Implementation

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.

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

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