Why can't I use a generic type to implement a non-generic signature

I am a little confused by the Java compiler.

I have an interface that has a method signature with "Object":

public interface Bean {
    public void setCreated(final Object created);
}

      

I would like to implement it with a generic:

public class BeanImpl<T extends Object> implements Bean{
        private T created;

        public void setCreated(final T created){
            this.created = (T)created;
        }
}

      

However, this raises a compiler error:

Name clash: The method setCreated(T) of type BeanImpl<T> has the same erasure as setCreated(Object) of type Bean but does not override it

      

Given that it T

is Object () by definition , why doesn't the compiler let me create this construct? Attempting to mark this @Override

just generates an error that the method does not actually override the supertype. It's almost as if the compiler doesn't understand / see what T

the object really is.

+3


source to share


1 answer


If allowed, someone could potentially create

public class Child extends BeanImpl<Integer> {
    public void setCreated(Integer created){
        // whatever
    }
}

      

and



Bean bean = new Child();
bean.setCreate(new NotAnInteger());

      

and type safety will be violated. You must complete the interface.

+7


source







All Articles