What would be the use of accepting itself as type arguments in generics

后端 未结 2 916
北荒
北荒 2021-02-05 23:30

I saw some code on an unrelated question but it got me curious as I never saw such construct with Java Generics. What would be the use of creating a generic class that can take

2条回答
  •  日久生厌
    2021-02-06 00:03

    Generics aren't just for containers like lists. This sort of "extends itself" type parameter is used to let the superclass refer to the subclass in places like method parameters and return types, even though no actual specific subclass is available when the superclass is compiled. It's analogous to the curiously recurring template pattern in C++.

    A subclass of your example would be declared as

    class Foo extends A
    

    and the inherited foo() method becomes

    void foo(Foo x)
    

    See how A defined a method that takes a Foo parameter even though it doesn't actually know about Foo?

    Yes, this sort of thing is unusual, but not unheard of: the built-in Enum class uses a similar trick.

提交回复
热议问题