I have a generic class with parameter that extends Paint. I really don’t understand why I should cast it manually to T in first constructor. What am i doing wrong? Or this is the case when the compiler can’t determine a safe cast itself?
public class XYPlot <T extends Paint> extends AbsPlot implements XYChartElement {
public XYPlot(AbsSeries series){
setUp(series, (T) new Paint(DEFAULT_PAINT));//TODO
}
public XYPlot(AbsSeries series, T paint){
setUp(series, paint);
}
private void setUp(AbsSeries series, T paint){
if(series == null) throw new NullPointerException("Series is null");
setSeries(series);
setPaint(paint);
}
You shouldn’t – you shouldn’t be creating an instance of just
Paintin the first place. ThatPaintwon’t be an instance ofT, unlessTis exactlyPaint. A generic class which only works properly for a single type argument shouldn’t be generic in the first place.If you need an instance of
Ton construction, you’ll either need the caller to pass one in, or take aClass<T>so that you can look through the constructors using reflection and call an appropriate one.Let’s look at a simpler version of what you’re doing, and hopefully you’ll see why it’s wrong:
Here we’re using
Objectinstead ofPaint– but otherwise, it’s basically similar.Now if we call it:
… what would you expect that to do?
Fundamentally it’s not clear why you have made your class generic in the first place – but the approach you’re taking is inherently flawed.