java lang涉及抽象类的NullPointerException?

时间:2014-11-20 20:13:52

标签: java nullpointerexception abstract-class

现在我知道无法启动抽象类。但我一直在阅读java.lang.NullPointerException,人们认为这是由仍然指向null的字段引起的。我已经通过ComputerPart初始化了继承的超类方法,但我仍然收到错误。我正在上网,因此您的意见非常重要。谢谢。

abstract class Product {
    protected float price;
    public static int i = 0; // to keep count starts at zero 
    protected static int ID ; // to update and keep track of ID even if i changes 
    // return the price of a particular product
    abstract float price();
}

//------------------------------------------------------------

class ComputerPart extends Product {

    public ComputerPart(float p) {
        i += 1; // each time constructor invoked ,  
        ID = i; // to update ID even if i changes.
        price = p;
    }

    public float price() { return price; }

    // a getter method so ID can be nicely formated and returned
    public static String getID(){ 
        String Identification =  "ID#" + ID;
        return Identification;
    }
}  

//------------------------------------------------------------
import java.util.*;

public class GenericOrder <T extends Product>  {
    ArrayList<Product> genericOrder; 

    public String comPrice(float comPrice){
        genericOrder.add(new ComputerPart(comPrice));
        String s;
        s="Computer Part, Price=$ "+comPrice;
        return s;
    }
}

我的测试类是

GenericOrder gen = new GenericOrder<Product>(); 
gen.comPrice(0);

1 个答案:

答案 0 :(得分:3)

从不初始化genericOrder。变化

ArrayList<Product> genericOrder;

ArrayList<Product> genericOrder = new ArrayList<Product>();