Visonil Hendric
Visonil Hendric

Reputation: 1

Can you change the value of a variable, but have all other things that were instantiated with the old value change to the new value?

I have a homework where I have to create a class that has an input, and output and a lot of other elements in between.

I need to build a constructor that creates all the other elements from a file, but I do not have the input in the file. The input is supposed to be set with a method called setInput().

Unfortunately the constructor instantiates some elements that have the input as a parameter. Is there any possible way in which when I call the setInput method to variables from the elements I instantiated earlier?

Upvotes: 0

Views: 41

Answers (1)

VHS
VHS

Reputation: 10174

You have two choices:

  1. Pass the 'input' to the constructor as an argument and let the constructor use its value while initializing the 'elements'.
  2. Have private or public setter methods for each of your elements (called fields of your class) take 'input' as argument. Call those setters from your 'setInput' method. Look at the following sample:

    public class MyClass { Integer element1; String element2;

    public MyClass() { element1 = new Integer(); element2 = ""; }

    private setElement1(Object input){ //Set element1 from information contained in 'input' this.element1 = ...

    }

    private setElement2(Object input){ //Set element2 from information contained in 'input' this.element2 = ...

    } public setInput(Object input) { this.setElement1(); this.setElement2(); } }

Upvotes: 1

Related Questions