首页 > 解决方案 > 类对象未在主类中创建并给出 NullPointerException 错误

问题描述

我有三个班Product,,,Cart。类与类继承。类具有主要功能,我正在尝试创建 Cart 类的对象。但它没有被创建。这是我的家庭作业,他们提到我必须在 Cart 类中使用 ArrayList 并在 Shop 类中创建 Cart 的对象。如果我用 Shop 类继承 Cart 类, 那么我可以使用 Cart 类但我不能像这样提交它我必须在 Shop 中创建 Cart 的对象并且必须使用它ShopCartProductShoppublic class Shop extends Cart{ .... Methods

错误:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Cart.a
ddItem(Product)" because "this.myCart" is null
        at BookShop.addItem(BookShop.java:109)
        at BookShop.showGUI(BookShop.java:42)
        at BookShop.main(BookShop.java:10)

这是类,它们是一段代码,而不是整个程序。

产品.java

public class Product {
    private String name;
    private int quantity;

    public Product(){
        System.out.println("Object Created");
        name = null;
        quantity = 0;
    }
    
    public Product(String name,int quantity){
        this.name = name;
        this.quantity = quantity;
    }
    public Product(Product p){
        this.name = p.name;
        this.quantity = p.quantity;
    }
    public void setName(String Name){
        this.name = Name;
    }
    public void setQuantity(int quantity){
        this.quantity = quantity;
    }
    public String getName(){
        return this.name;
    }
    public int getQuantity(){
        return this.quantity;
    }
}

购物车.java

import java.util.ArrayList;

public class Cart extends Product{
    private ArrayList<Product> CartItems;

    public Cart(){
        super();
        System.out.println("Object Created");
        CartItems = new ArrayList<Product>();
        

    }
    public Cart(String name,int quantity){
        super(name,quantity);
    }
    public Cart(Cart c){
        this.CartItems = c.CartItems;
    }
    public void addItem(Product p){
        this.CartItems.add(p);
    }
    public void setCart(ArrayList<Product> cart){
        CartItems = cart;
    }
    public ArrayList<Product> getList(){
        return this.CartItems;
    }
}

商店.java

import javax.swing.JOptionPane;

public class Shop{
    public Cart myCart;
    public static void main(String[] args) {
        Shop myShop = new Shop();
        myShop.showGUI();
    }
    public Shop(){
        
    }
    public Shop(Shop s){
        this.myCart = s.myCart ;
    }

    public Shop(Cart c){
        this.myCart.setCart(c.getList());
    }

    public void showGUI(){
        
        String input= JOptionPane.showInputDialog("Enter Quantity");
        Integer qualtiy = Integer.parseInt(input);
        Product p = new Product("Book", qualtiy);

        this.myCart.addItem(p);
        }
    

}

标签: javaclassnullpointerexception

解决方案


推荐阅读