Search code examples
javagenericsjava-6

Possible to add generics to implementation of a non-generic interface in Java?


Is it possible to generify an implementation of the interface if the interface definition does not use generics? I do not have control over the interface I need to implement, but would like to suppress "unchecked" warnings for my implementation.


Solution

  • Some issues can be resolved, some can not.

    If the interface for instance looks like this:

    interface OldInterface {
        List someMethod();
    }
    

    then sure, you can implement it by

    class NewClass implements OldInterface {
        public List<String> someMethod() {          // DOES COMPILE.
            ...
        }
    }
    

    If, on the other hand, the interface looks something like

    interface OldInterface {
        void someMethod(ArrayList list);
    }
    

    then there's nothing you can do about it programming wise.

    class NewClass implements OldInterface {
        public void someMethod(ArrayList<String> list) { // DOES NOT COMPILE.
            ...
        }
    }
    

    This is what is referred to as an unavoidable generic type problem. Luckily these warnings can be suppressed, at least in Eclipse, by checking Ignore unavoidable generic type problems under

    Windows > Preferences > Java > Compiler > Errors/Warnings