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

后端 未结 4 1666
走了就别回头了
走了就别回头了 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:12

    Jen, your question doesn't put any context around why you want to use a generics. It would really be helpful if you stated what it is you are trying to do and why you are using generics. Generics exist IMHO mainly to avoid having to do class casts everywhere when putting things into and taking them out of collections that are designed to be generic holders of types. This kinda implies iteration over a bunch of things, but not necessarily.

    My point is, I didn't see any part of your class or code that required being able to create a custom version of the monkey class that required iterating over environments. If this is not the case, you probably don't even need generics. Instead, you probably want dependency injection. The monkey class should have a constructor that takes an environment. Environment is an interface (or simple base class). The interface has several default operations like getBathroomLocation() and getFoodLocation(). Instead of using generics to create a type of monkey that lives in the zoo, you create a monkey and inject the dependency of which environment it lives in.

    Monkey monkey = new Monkey(new CostaRicaJungle());
    

    Later on, you can set this environment to something different. The wild monkey gets captured, and you now do

    monkey.setEnvironment(new BronxZoo());
    

    Later, the monkey gets an living condition change, and you do a

    monkey.setEnvironment(new SanDiegoZoo());
    

提交回复
热议问题