JKawa JKawa - 7 months ago 37
Java Question

Modify an instance variable within the Main class or main method

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.


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;