-4

I would like to be able to modify the value of a local variable defined in a constructor within the class via the main driver class at some point while running the program. How would I be able to achieve this?

Here is a sample of a constructor that I am using.

public Scale()
{
    weight = 0;
    unit = "kg";
}

I'd like to modify the value of weight at a point while running the program in the driver.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
JKawa
  • 179
  • 2
  • 6
  • 20
  • Those aren't local variables. What have you tried? Do you know how to construct an instance of your object? Do you have getters and setters? – OneCricketeer Nov 14 '16 at 03:45
  • 1
    @cricket_007: it looks like he needs to read a java text on exactly that -- getter and setter methods. Answered as a community wiki, but I'm also voting to close as this is best answered by his studying any basic Java text. – Hovercraft Full Of Eels Nov 14 '16 at 03:47

2 Answers2

1

It sounds like you're wanting to give the class a method that would allow outside code to be able to change or "mutate" the state of the fields of the class. Such "mutator" methods are commonly used in Java, such as "setter" methods. Here, public void setWeight(int weight):

public void setWeight(int weight) {
    this.weight = weight;
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • Can't believe I didn't figure it out. I already had a setter/mutator exactly similar to this but it didn't click in my head. Classes are still fairly new to me. Thanks! – JKawa Nov 14 '16 at 03:58
-1

The best way to allow that would probably be through a method. It could be something as straightforward as setWeight(), or something more complicated like a method for adding items to the scale...

public class Scale {

    private float weight = 0;
    private String unit = "kg";

    public void setWeight(float weight) {
        this.weight = weight;
    }

    public void addItem(Item i) {  // Assumes that Item is an interface defined somewhere else...
        this.weight += i.getWeight();
    }

    public static void main(String[] args) {
        Scale s = new Scale();
        s.setWeight(4.0F);  // sets the weight to 4kg
        s.addItem(new Item() {
            @Override
            public float getWeight() {
                return 2.0F;
            }
        });  // Adds 2kg to the previous 4kg -- total of 6kg
    }

}
Drew Wills
  • 8,408
  • 4
  • 29
  • 40