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
s, such as Jungle
or Zoo
:
public class Monkey<T extends Environment> { T home; ... public T getHome() { return home; } }
Is there a way to specify a default for T
, so I can use the type Monkey
instead of Monkey<?>
without getting a compiler warning?
EDIT
In other words, is there a way to get rid of the "raw type" warning without having to explicitly suppress it?
Java For Testers Whenever you want to restrict the type parameter to subtypes of a particular class you can use the bounded type parameter. If you just specify a type (class) as bounded parameter, only sub types of that particular class are accepted by the current generic class.
To update the Box class to use generics, you create a generic type declaration by changing the code "public class Box" to "public class Box<T>". This introduces the type variable, T, that can be used anywhere inside the class. As you can see, all occurrences of Object are replaced by T.
No, you can't do that. Generic parameters don't have default values. You could re-organize your type hierarchy so that there's a GenericMonkey and a DefaultMonkey that sets the generic parameter to your desired default.
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<YourType>
Obviusly you'll "waste" the ability to inherit.
EDIT 1: Another interesting thing is do the reverse of what I suggested,
public class Monkey<T> 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With