Calling constructor of a generic type

后端 未结 6 1711
借酒劲吻你
借酒劲吻你 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:14

    T is an alias for the actual type your class will handle, for example if you instantiate Box then T is really just an alias for Item. As you declare T extends Item then you know that T will have at least the same interface as Item, so you can treat it like one.

    I think what you really want to do is not instantiate the item field in Box, but instead implement a couple of methods to let you manipulate that field.

    public class Box {
        private T item;
    
        public T getItem() {
            return this.item;
        }
    
        public void setItem(T item) {
            return this.item = item;
        }
    }
    

提交回复
热议问题