对象未获得Java中的属性

我这里有两节课:

public class PizzaTester 
{
    public static void main(String[] args)
    {
        // Test your Pizza class here.
        System.out.println(new Pizza("Veggie", "Tomatoes, onions, olives", 12));
        System.out.println(new Pizza("Cheese", "Cheese", 15));
        System.out.println(new Pizza("Meat", "Popperoni, sausage, bacon", 20));
    }
}
public class Pizza
{
    // Add the instance variables here
    private String type;
    private String toppings;
    private int size;

    // Put the constructor here
    public Pizza(String theType, String theToppings, int theSize){
        theType = type;
        theToppings = toppings;
        theSize = size;
    }


    // You don't need to do anything with this method
    // Used to print the object
    public String toString()
    {
        return size + " inch " + type + " pizza with " + toppings;
    }
}

我得到的输出是:

0 inch null pizza with null
0 inch null pizza with null
0 inch null pizza with null

有人可以帮助我了解为什么它没有按我希望的方式打印。我知道,如果我事先制作三个对象然后打印它们,代码将起作用,但是我不是在做同样的事情吗?是否因为要打印信息而需要一个对象来保存信息?

评论
  • yalias
    yalias 回复

    You made a typo in the constructor param assigning. Changing it from theSize = size to `size = theSize' should work.

    这是更新的构造函数代码:

    public Pizza(String theType, String theToppings, int theSize){
        theType = type;
        theToppings = toppings;
        size = theSize;
    }
    
  • xnemo
    xnemo 回复
    public Pizza(String theType, String theToppings, int theSize){
            this.type= theType;
            this.toppings= theToppings;
            this.size= theSize;
        }
    

    是构造函数的正确版本。您正在将局部变量设置为参数。