Lower bounded wildcard not checked against upper bounded type parameter

前端 未结 4 2358
耶瑟儿~
耶瑟儿~ 2021-02-20 03:01

I wonder why does this piece of code compile successfully?

Source code:

abstract class A
{
    public abstract  A

        
4条回答
  •  南旧
    南旧 (楼主)
    2021-02-20 03:07

    This is a surprisingly meaningless piece of code.

    All it is saying is that the class A takes a generic type K that is a Number and there is a method useMe that returns an A with some pointless extra restriction on T (other than being a Number obviously).

    Here's an implementation to show how little is being said by the sugar:

    abstract class A {
        public abstract  A useMe(A k);
    }
    
    class B extends A {
    
        @Override
        public  A useMe(A k) {
            // Not much more you can do here but this.
            return k;
        }
    
    }
    

    The ? super M stuff is just meaningless gobbledegook - all the compiler can derive from it is that both the parameter passed to it and the result returned must be a superclass of a specific unnamed class.

    Generics are there to make detection of coding mistakes easy at compile time. Using mumbo-jumbo such as this is just misleading obfuscation.

提交回复
热议问题