Ramy Al Zuhouri Ramy Al Zuhouri - 6 months ago 9
Java Question

Calling constructor of a generic type

If I have an abstract class like this:

public abstract class Item
{
private Integer value;
public Item()
{
value=new Integer(0);
}
public Item(Integer value)
{
this.value=new Integer();
}
}


And some classes deriving from Item like this:

public class Pencil extends Item
{
public Pencil()
{
super();
}
public Pencil(Integer value)
{
super(value);
}
}


I have not understood why I can't call the constructor using a generic:

public class Box <T extends Item>
{
T item;
public Box()
{
item=new T(); // here I get the error
}
}


I know that is possible to have a type which hasn't a constructor, but this case is impossible because Pencil has the constructor without parameters, and Item is abstract.
But I get this error from eclipse:
cannot instanciate the type T

I don't understand why, and how to avoid this?

Answer

There is no way to use the Java type system to enforce that a class hierarchy has a uniform signature for the constructors of its subclasses.

Consider:

public class ColorPencil extends Pencil
{
    private Color color;

    public ColorPencil(Color color)
    {
        super();
        this.color=color;
    }   
}

This makes ColorPencil a valid T (it extends Item). However, there is no no-arg constructor for this type. Hence, T() is nonsensical.

To do what you want, you need to use reflection. You can't benefit from compile-time error checking.

Comments