0

Essentially I'm trying to do something that is stated here Changing variables in multiple Python instances but in java.

I want to reset a variable in all instances of a certain class so something like:

public class NewClass{
int variable = 1;
}

then:

NewClass one = new NewClass();
NewClass two = new NewClass();
NewClass three = new NewClass();

Newclass.variable = 2;

System.out.println(one.variable);
System.out.println(two.variable);
System.out.println(three.variable);

output would be:

2
2
2

is there a way to do that?

2
  • Should value of variable always be the same for each instance? If yes then you can make that variable static via static int variable = 1; which would mean it doesn't belong to instances but to class. Commented Jan 4, 2020 at 15:01
  • 2
    Just make the field static. But this seems pretty much like an XY problem to me. What are you actually trying to do? Commented Jan 4, 2020 at 15:01

4 Answers 4

0

Please use static variable

public class NewClass{
    static int variable = 1;
}

Important facts about static variable, please check

  1. If the value of a variable is not varied from object to object such type of variables is not recommended to declare as instance variables. We have to declare such type of variables at class level by using static modifier.
  2. In the case of instance variables for every object a separate copy will be created but in the case of static variables for entire class only one copy will be created and shared by every object of that class.
  3. Static variables will be crated at the time of class loading and destroyed at the time of class unloading hence the scope of the static variable is exactly same as the scope of the .class file.
  4. Static variables will be stored in method area. Static variables should be declared with in the class directly but outside of any method or block or constructor.
  5. Static variables can be accessed from both instance and static areas directly.
  6. We can access static variables either by class name or by object reference but usage of class name is recommended. But within the same class it is not required to use class name we can access directly.
Sign up to request clarification or add additional context in comments.

Comments

0

Make that variable static so that it is now a property of the class and not an instance.

public class NewClass{
  static int variable = 1;
}

Comments

0

Mark the attribute static.

public class NewClass {
static int variable = 1;
}

Comments

0

java does not support multiple instance...but you csn solve this problem using interface. ex. public interface abc

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.