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
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";