Alex Rivera | Logout

Java: How to set a default for "T" in SomeClass<T>?

Asked 2011-05-23T18:53:59.680
47

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 Environments, 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?

Edit
Report

1 Answer

10

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.

answered 2011-05-23T18:59:23.550

Your Answer