简体   繁体   English

如何从另一个 class 传递 class 参考?

[英]How do I pass a class reference from another class?

I'm building a basic beginner Java program but I keep getting the NullPointerException error and I can't seem to solve the problem.我正在构建一个基本的初学者 Java 程序,但我不断收到 NullPointerException 错误,我似乎无法解决问题。

I have two classes - User and Cart.我有两个类 - 用户和购物车。

The User class includes the Cart class with the following code:用户 class 包括带有以下代码的购物车 class:

package eCommerceApp;

import java.util.List;
import java.util.Collections;
import java.util.Comparator;

public class User extends Person {

    public User(String name, String surname, int budget) {
        super(name, surname, budget);
    }

    public Cart myCart;

    public String getReceipt(List<Product> products) {

        int sum = 0;

        for (Product product : products) {

            sum += product.getPrice();
        }
        return "Your total bill is " + sum + " rsd.";
    }

    public String getMostExpensiveItem(List<Product> products) {

        Product product = Collections.max(products, Comparator.comparing(s -> s.getPrice()));

        return "The most expensive item in your shopping cart is " + product.getName() + ".";

    }

    public String getCheapestItem(List<Product> products) {

        Product product = Collections.min(products, Comparator.comparing(s -> s.getPrice()));
        return "The cheapest item in your shopping cart is " + product.getName() + ".";

    }

}

And the Cart Class:还有购物车 Class:


import java.util.List;

public class Cart {

    List<Product> products;

    public Cart(List products) {

        this.products = products;
    }

    public String getProducts() {
        return this.products.toString();
    }

    public void setProducts(List products) {
        this.products = products;
    }

}

Now, when I want to set a list of products to my User's Cart by typing User.myCart.setProducts(list) in the main class, I get the NullPointerException error.现在,当我想通过在主 class 中键入User.myCart.setProducts(list)将产品列表设置到我的用户购物车时,我收到 NullPointerException 错误。 How can I solve this?我该如何解决这个问题?

To use classes in other classes, you'll need to make an instance of them like so:要在其他类中使用类,您需要像这样创建它们的实例:

public Cart myCart = new Cart();

Unless your entire class is static, this is the way to go.除非您的整个 class 是 static,否则这是 go 的方式。 But it is generally not good practice to make your classes static all the time.但始终让您的课程 static 通常不是一个好习惯。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM