What does <T extends mean?

后端 未结 7 1560
庸人自扰
庸人自扰 2020-12-12 22:00

I have seen a method like shown below:

protected  T save( T Acd, boolean en) {

What does it do? What is these type of

7条回答
  •  隐瞒了意图╮
    2020-12-12 22:44

    protected  T save( T Acd, boolean en) {
        // ...
    }
    

    In this function, there are two places we should pay attention to

    • bounded type parameter:
    • returned-type: T

    Based on those, I can answer your questions as following

    What does it do?

    save() is a generic method that returns a value of type T. T is a generic type, that is restricted to ABC. The scope of T is limited to save().

    What is these type of method declarations called in Java?

    IMO, the answer should be bounded type parameters, instead of generics. More about generics in Java, you can find here.

    One more question I would like to add by myself: Why do we want such thing?

    There may be times when you want to restrict the types that can be used as type arguments in a parameterized type. For example, a method that operates on numbers might only want to accept instances of Number or its subclasses. This is what bounded type parameters are for [1].

提交回复
热议问题