Java: How to set a default for “T” in SomeClass?

后端 未结 4 1698
走了就别回头了
走了就别回头了 2020-12-11 14:35

Is there a way to specify a default type for a generic template?

Let\'s say I have a Monkey class. Monkeys can live in different Environment

4条回答
  •  余生分开走
    2020-12-11 15:15

    No you can't: http://en.wikipedia.org/wiki/Comparison_of_Java_and_C%2B%2B

    Generic type parameters cannot have default arguments.

    What about making something like this:

    public class Monkey extends Monkey
    

    Obviusly you'll "waste" the ability to inherit.

    EDIT 1: Another interesting thing is do the reverse of what I suggested,

    public class Monkey extends Monkey
    

    In this case all generics class Monkey inherits Monkey, in some cases, this is a very interesting thing (expecially when you notice that some instance-methods fits in all classes without requiring the generic). This approach is used in Castle ActiveRecord (I've seen it used in C#, not in Java), and I find it beautiful.

提交回复
热议问题