Java string returns as null

前端 未结 4 1036
梦如初夏
梦如初夏 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";
    
    0 讨论(0)
  • 2021-01-28 02:16

    In IceCream class constructor you have:

    String flavour = getFlavour()
    

    You have created a local variable instead a reference to a instance property. getFlavour() method return the property instance that you never set, so its null. You should have something like this in the constructor:

    this.flavour = "default value";
    

    Or set a flavour parameter on constructor header:

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

    And call it like:

    IceCream chocolat = new IceCream(" chocolat");
    

    And if you want change the flavour use the setter.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-28 02:30

    You never call flavour.setFlavour(), so it's no surprise flavour.getFlavour() returns null.

    0 讨论(0)
提交回复
热议问题