Java – why can’t I use generic types to implement non generic signatures

I'm a little confused about the java compiler

I have an interface with "object" method signature:

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

I want to implement it with generics:

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

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

However, this results in compiler errors:

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

By definition, t is an object (). Why doesn't the compiler allow me to create this construct? Trying to mark it as @ override just generates an error message, and the method does not actually override the supertype It's almost like the compiler doesn't understand / see that t is actually an object

Solution

If allowed, someone may 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 break You must meet the requirements of the interface

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>