In my Java project I have an abstract class using a generics type. My class is extended and implemented by some concrete subclasses. My source code is something like this:
class Metrics<T extends Dataset>
{
public float evaluate(T dataset, Entity x, Entity y);
}
class MetricsType1 extends Metrics<DatasetType1>
{
public float evaluate(DatasetType1 dataset, Entity x, Entity y);
}
class MetricsType2 extends Metrics<DatasetType2>
{
public float evaluate(DatasetType2 dataset, Entity x, Entity y);
}
In my main application I use my classes in this way:
Metrics<DatasetType1> metrics1 = new MetricsType1();
Metrics<DatasetType2> metrics2 = new MetricsType2();
I would like to use the same reference "metrics" instead of having two different references "metrics1" and "metrics" so that I could instance my "metrics" reference with a MetricsType1 or a MetricsType2 class without having to write two separate references.
In particular I would like to write something like this:
Metrics metrics = null;
metrics = new MetricsType1();
// ...
metrics = new MetricsType2();
Obviously the Java interpreter gives me a warning telling me I should use a parameter for the generics of the class Metrics.
How could I handle this?
Thank you!
Use wildcards:
Metrics<?> metrics;
or, if you ant to be more specific:
Metrics<? extends Dataset> metrics;
In this particular case, those are both synonyms, as Metrics
is defined so that T extends Dataset
.
Notice, however, that with this definition the evaluate
method cannot be called directly. You will have to cast the object to a concrete subclass to do it.