JKawa JKawa - 1 year ago 79
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.

Answer Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download