Immanuel Immanuel - 2 years ago 88
Java Question

How can I convert an input (int, String, etc) to a final variable of the same kind?

lets say I'm constructing a FoodItem, and I want to enter a new item, I want to make sure that the item's name cannot be changed and so does the price of it (meaning I cannot use Setter to change it) but I will be able to change the quantity.

My question is as follows: by declaring the finals NAME and COST in the constructor I cannot access them out side of it, for example for a method like getName() or getCost().
I hope my question is clear enough, if not just ask and I'll reply.

I'm still a beginner at java so forgive me if I'm missing something obvious, I'm here to learn!

public class FoodItem {

private int _quantity;

public FoodItem (String name, int cost, int quantity){ //
final String NAME = name;
final int COST = cost;
_quantity = quantity;

public String getName(){ return NAME;} //<-- obviously cannot be found
public int getCost(){ return _cost;}
public int getNumber(){ return NUMBER;}
public void setCost(int newCost){ _cost = newCost;}

zeb zeb
Answer Source

NAME and COST are declared in the wrong spot. Move their declaration where _quantity is declared.

private int _quantity;
private final String NAME;
private final int COST;

public FoodItem (String name, int cost, int quantity){ 
    NAME = name;
    COST = cost;
    _quantity = quantity;

See answer here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download