首页 > 解决方案 > java中的java.lang.NullPointerException错误

问题描述

我正在尝试用 Java 建造一个车库。当我在我的主“测试”中对我的对象 Lagouna 调用方法 addOption 时,我得到了 NullPointerException。这很奇怪,因为它在我调用我的方法 setMoteur 时起作用。我的对象 Lagouna 不为空。我的对象 GPS 也不为空。

主要的

public class Test {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
     Garage garage = new Garage();   
     System.out.println(garage);

     Vehicule lag1 = new Lagouna();
     lag1.setMoteur(new MoteurEssence("150 Chevaux", 10256d));
     lag1.addOption(new GPS()); // here is my error

    }
}

类车

public abstract class Vehicule {

protected double prix;
protected String nom;
protected Marque nomMarque;
protected List<Option> options;
protected Moteur moteur;


Vehicule(double prix,String nom,Marque nomMarque){
    this.prix=prix;
    this.nom=nom;
    this.nomMarque=nomMarque;
}
Vehicule(){
    prix=0d;
    nom="";
    nomMarque=null;
    options=null;
    moteur=null;
}
public String toString() {
    String str="Je suis une voiture "+ nom + " de la marque "+ nomMarque;
    return str;
    }

public void addOption(Option opt) {
    options.add(opt);
        }
public Marque getMarque() {
    return nomMarque;
    }
public List<Option> getOptions() {
    return options;
    }
public double getPrix() {
    return prix;
    }
public void setMoteur(Moteur mot) {
    this.moteur=mot;
    }
}

类泻湖

public class Lagouna extends Vehicule {

    Lagouna(){
        super();
    }
}

GPS类

public class GPS implements Option{

static double prix=113.5d;
    public double getPrix() {
        return prix;
    }
}

类选项

public interface Option {

public double getPrix();
}

标签: java

解决方案


推荐阅读