SIMEL
SIMEL

Reputation: 8931

Creating default generic type for a class in Java

I want to create an object that will have two generic types, but in some places it's created with only one generic type given. In those cases the second type is of no importance, so I want to be able to give an option for creating the class with only one generic type, and the other generic type to be set by default to Object, something that will look like (in C++ style):

public class myClass<T,O=Object> {...
}

Since I know there aren't default values in Java, I don't expect to have default types, but are there any ways to create some thing similar (maybe class override)?

Upvotes: 3

Views: 1354

Answers (2)

Mairbek Khadikov
Mairbek Khadikov

Reputation: 8089

Creating a subclass seems to be an overhead I would use a static factory method.

public class MyClass<T, O> {
    ...

    <T> public static MyClass<T, Object> create(...)
    ...
}

Upvotes: 5

Tom
Tom

Reputation: 19304

The typical way to accomplish this is to subclass "myClass".

That is to say, suppose you have


public class MyClass<T, O>
{}

You make a subclass


public class DefaultMyClass<T> extends MyClass<T, Object>
{}

This may not be as elegant as you want, but it's really the only way to accomplish this.

Upvotes: 0

Related Questions