简体   繁体   中英

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.

I have two classes - User and Cart.

The User class includes the Cart class with the following code:

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:


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. 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. But it is generally not good practice to make your classes static all the time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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