Compilation error when overriding the abstract enumeration method with a common return type

Here is the code that compiles correctly

public enum SupportedConversions {
    INTEGER {
        @Override
        public Integer convert( String ion, Object[]  aa) {
            return null;
        }
    },
    LONG {
        @Override
        public Long convert(final String ion, Object[] aa) {
            return null;
        }
    };

    public abstract <T> T convert(String val, Object[] aa);
}

But when I change the parameter of an abstract function to a list of objects, and not to an array, I get a compilation error: "The method does not override from the superclass." and this only happens if the return type is general

bad code example

public enum SupportedConversions {
    INTEGER {
        @Override
        public Integer convert( String ion, List<Object>  aa) {
            return null;
        }
    },
    LONG {
        @Override
        public Long convert(final String ion, List<Object> aa) {
            return null;
        }
    };

    public abstract <T> T convert(String val, List<Object> aa);
}

Is there a reason this doesn't work. It seems like a bug in Java

+4
source share
1 answer

The question should be “why the first can be compiled”, and not “why the second crashes”.
Both are broken.

Method signature e.g.

<T> T convert(String val, Object[] aa)

" , T, ". , null, , , , .

,

Long convert(final String ion, Object[] aa)

, , promises , Long. ... - , null, , null Long, , Long Long.

. ,

String s = SupportedConversions.LONG.convert("bla", null);

. , <T> T convert(…) promises , T, T String. , , , Long.


, , - pre-Generics. , "" . . Java 1.4 jdk, .

, convert , Generics, convert . , ,

Long convert(final String ion, List<Object> aa)

Generics, , Generic type. List, - , Generics.


, , . , ( enum), , enum, , Java 5 ( Generics).

, , Long . Integer, Object, Java 5.

( ) . . ( , NetBeans ), .


. , , enum s. T Object, enum , API public. :

public interface SupportedConversions<T> {
    SupportedConversions<Integer> INTEGER = (String ion, Object[] aa) -> {
        return null;
    };
    SupportedConversions<Long> LONG = (String ion, Object[] aa) -> {
        return null;
    };
    public abstract T convert(String val, Object[] aa);
}

.

public interface SupportedConversions<T> {
    SupportedConversions<Integer> INTEGER = (ion, aa) -> {
        return null;
    };
    SupportedConversions<Long> LONG = (ion, aa) -> {
        return null;
    };
    public abstract T convert(String val, List<Object> aa);
    // we can support both variants
    public default T convert(String val, Object[] aa) {
        return convert(val, Arrays.asList(aa));
    }
}
+1

Source: https://habr.com/ru/post/1671498/


All Articles