Java string returns as null

前端 未结 4 1131
梦如初夏
梦如初夏 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:21

    Flavour is not initialized private String flavour; as anything, when calling IceCream() you set String flavour = getFlavour(), which sets the local variable flavour inside the constructor to null, because getFlavour() returns null. Also the local String flavour variable inside the constructor overshadows the String flavour field of your IceCream class. Try making flavour a parameter of the constructor and then setting the field to that string

    public IceCream(String f) {
        this.flavour = f;
        price = 0.50;
    }
    

    or call setFlavour() before you work with the object you created.

提交回复
热议问题