I implemented the following Java classes:
public class Data<T> { private List<T> data; public List<T> getData() { return this.data; } public Data<T> setData(List<T> data) { this.data = data; return this; } public Data<T> getAsNullIfEmpty() { if (this.data == null || this.data.isEmpty()) return null; return this; } } public class IntegerData extends Data<Integer> {} I would like the getAsNullIfEmpty() method to be able to be called by its subclasses instances.
The line IntegerData integerData = new IntegerData().getAsNullIfEmpty(); throws the following compilation error: incompatible types: Data<java.lang.Integer> cannot be converted to IntegerData
I tried changing the body of the method getAsNullIfEmpty() to this:
public <E extends Data<T>> E getAsNullIfEmpty() { if (this.data == null || this.data.isEmpty()) return null; return this; } This doesn't compile though because Data<T> does not extend itself. Is there a way to accomplish this without recurring to overriding the method in each of the child classes or using an explicit cast?