Calling constructor of a generic type

后端 未结 6 1706
借酒劲吻你
借酒劲吻你 2020-12-10 12:48

If I have an abstract class like this:

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


        
6条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-10 13:22

    You can place an abstract method so that the implementing class can determine how to construct the new object.

    public abstract T constructT();
    

    and instead of calling

    T t = new T()
    

    you would call

    T t = constructT();
    

    On your implementing call it would be created as:

    new Box() {
        public Integer constructT(){ return new Integer(); }
    }
    

提交回复
热议问题