java - 类对象未在主类中创建并给出 NullPointerException 错误
问题描述
我有三个班Product
,,,Cart
。类与类继承。类具有主要功能,我正在尝试创建 Cart 类的对象。但它没有被创建。这是我的家庭作业,他们提到我必须在 Cart 类中使用 ArrayList 并在 Shop 类中创建 Cart 的对象。如果我用 Shop 类继承 Cart 类,
那么我可以使用 Cart 类但我不能像这样提交它我必须在 Shop 中创建 Cart 的对象并且必须使用它Shop
Cart
Product
Shop
public 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);
}
}
解决方案
推荐阅读
- vim - 尽管没有备份,VIM 错误 E510 “无法制作备份文件”
- c# - 无法在 Azure DevOps 上完成拉取请求
- .net-core - VS 2017 .Net Core 项目模板
- io - C fgets 函数的等效 Chapel 功能
- google-apps-script - 在我的 G Suite 域中的 Google 表格中记录工作表用户名时禁用脚本授权
- python - 数据集中的目标,图像 [0] sklearn
- r - 如何实现提取/分离功能(来自 dplyr 和 tidyr)以将一列分成多列。基于任意值?
- python - 抓取阿拉伯网站时从阿拉伯字母中获取奇怪的字母
- java - 如何使用 Java 查询 Grakn?
- javascript - 如何在 Jest 中的多个测试套件之间共享一个对象?