davorp
davorp

Reputation: 4236

Optional parametrization in Java with Generics

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
}

Upvotes: 14

Views: 12629

Answers (3)

Vanya
Vanya

Reputation: 3319

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
}

Upvotes: 0

Tim Bender
Tim Bender

Reputation: 20442

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).

Upvotes: 1

Eugen
Eugen

Reputation: 8783

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

Upvotes: 19

Related Questions