Stanislav Screbets Stanislav Screbets - 2 months ago 10
Java Question

What does "super(Car.class);" do in a constructor?

I am a beginner in java. Please explain me what does "super(Car.class);" do in a constructor?

public class CarDaoImpl extends AbstractDaoImpl<Long, Car> implements CarDao {

public CarDaoImpl() {
super(Car.class);
}
}

Answer

From what you posed in your question I assume the class AbstractDaoImpl to be something like this:

public class AbstractDaoImpl<S, T> {
    public AbstractDaoImpl(Class<T> clazz) {
        ...
    }
}

public class CarDaoImpl extends AbstractDaoImpl<Long, Car> implements CarDao {
    public CarDaoImpl() {
        super(Car.class);
    }
}

So it requires the subclasses to give a class of <T> to them.

Why is this done?

You may have heard of type erasure in Java, meaning that all the generics information will be gone on runtime.

Passing references to the classes is a way of keeping this information also on run-time when it might be needed.

Reflection

In this special case the type of <T> could be determined via reflection. But it is a matter of taste and style, if we would do this or hand the class directly, as reflection is not very straight-forward to use.

Actually handing it directly is the only type-safe way to do so.

Comments