tags:

views:

262

answers:

3

Is is it possible to specify default type when parametrzing a class? Example:

// abstract class    
public abstract class AbsClass<T1 extends Par1Class, T2 extends Par2Class> {
        // code 
    }


// parametrized imlementation class
public class RealClass extends AbsClass<ClassThatExtendsPar1, ClassThatExtendsPar2Class> {
   // code
}

// non-parametrized imlementation class
public class RealClass extends AbsClass {
   // code
}

in my implementation I have to specify NONE or ALL parameters. Is possible to make the second parameter non-mandatory, something like this:

// abstract class    
public abstract class AbsClass<T1 extends Par1Class, T2 extends Par2Class : default Par2Class > {
        // code 
    }

// parametrized only mandatory imlementation class
public class RealClass extends AbsClass<ClassThatExtendsPar1> {
   // code
}
+7  A: 

Simple answer: no, java does not support default parametrizations like that.

Eugen
+3  A: 

There is never really a good reason to do this. Typically you specify generic type parameters because some method arguments take or return a parameter of that type. If unspecified were valid, that would seem to suggest you intended not to perform any meaningful implementation of those methods.

Anyway, to solve your perceived problem, just specify "Object" for any type parameter that you don't care to specify. Or extend the abstract class with another abstract class which has only one type parameter (specifying Object as the second type parameter in your extends call).

Tim Bender
From my point of view there is a good reason of doing this. Because my "optional parameter" (T2 extends Par2Class) is a Class that we use as a Value Object and is extended in lot's of other classes. If I dont't specify the T2, I just use the default methods from ValueObject. If I specify, I need specific methods and don't have to cast.I was thinking of introducing another class in the inheritance order, but I was curious about the optional parametrization. Thanks.
interstellar
A: 

Well, the correct solution for your case may be

// parametrized only mandatory imlementation class
public class RealClass<StillGeneric extends Par1Class>
extends AbsClass<ClassThatExtendsPar1, StillGeneric> {
    // code
}
Vanya
But I need "parametrized" methods from the AbsClass. If I parametrize the RealClass, in my case there is no use of it. Or am I misjudging something?
interstellar