Java string returns as null

前端 未结 4 1076
梦如初夏
梦如初夏 2021-01-28 01:46

I am attempting to get one class to return a string from another class, though the return I get is null. I have a set method that works in setting the string in the original cla

4条回答
  •  误落风尘
    2021-01-28 02:15

    The problem starts in the constructor of your IceCream class.

    private String flavour;
    
    public IceCream()
    {
        // initialise instance variables
        String flavour = getFlavour();
        price = 0.50;
    }
    
    public String getFlavour()
    {
      return flavour; 
    }
    

    The first problem is that you are shadowing your member variable flavour - you are declaring another variable with the same name but whose scope is restricted to the constructor. The second problem is you are assigning the value returned by getFlavour(), which is just an accessor that returns the member variable itself (whose initial value is null).

    To fix it you need to assign an initial value in the constructor

    public IceCream()
    {
        // initialise instance variables
        this.flavour = "Vanilla"
        price = 0.50;
    }
    

    Its also possible to assign the initial value when you declare it

    private String flavour = "Vanilla";
    

提交回复
热议问题