使用java中的对象,创建新对象后无法从main到达他

Yuv*_*evy 1 java object

在主要我写了这两个声明:

Account newAccount = new Account(name);
newAccount.addNewProduct();
Run Code Online (Sandbox Code Playgroud)

这是Account中的构造函数代码和属性:

private final int MAX_PRODUCTS = 50; //Assumes no more than 50 products per customer
private String name;        //Name of the customer
private int sum;            //Sum amount of the purchase
private Product[] productList;      //List of products for a customer 
private int productCounter;         //Counter for number of products

public Account(String name)
{
    Product[] productList = new Product[MAX_PRODUCTS]; //New empty list of products of the customer }
    productCounter = 0;
    sum = 0;
    name = name;
}
Run Code Online (Sandbox Code Playgroud)

我不知道为什么,但在这种方法:

public void addNewProduct()
{   
    System.out.println("Name is: " + this.name);
    productList[productCounter] = new Product();
    productCounter++;
} 
Run Code Online (Sandbox Code Playgroud)

虽然我在控制台中输入了一个名字,但它打印的名称为null ...它就像没有保存我创建的对象newAccount的属性.为什么?

Anu*_*oob 5

name = name不管用.你需要使用this.name = name

这是因为在使用时name请参考构造函数中的参数; 当你使用时this.name,请参考该字段.