1

Can you link two or more variables so that if you change the value of one the rest change to the same value as well?

I thought of making a method that does that but I wanna know if there is an easier way of doing this.

Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69
  • 1
    Seems like you just want to make those variables point to the same object – ernest_k Oct 15 '18 at 17:04
  • What have you tried till now? – Ritesh Nair Oct 15 '18 at 17:04
  • Yeah I saw something called pointers in c++ and thought that you could point to of them to each other and if you changed one the other one would follow – Alex Tanasa Oct 15 '18 at 17:07
  • You'll want to look at how java handles identity and equality: https://stackoverflow.com/questions/1692863/what-is-the-difference-between-identity-and-equality-in-oop#1692882 – jgreve Oct 15 '18 at 17:27

1 Answers1

1

I think this can help you:

JFrame a = new JFrame("A");

JFrame b = new JFrame("B");

a = b = new JFrame("C");

System.out.println(a.getTitle() + " - " + b.getTitle());

a.setTitle("D");

System.out.println(a.getTitle() + " - " + b.getTitle());

You assign same instance to multiple variables and after that change only one.

I used JFrame just as example.

P.S.: This works only for objects. For primitives(byte, short, int, long, float, double, boolean, char and String) doesn't. If you want to work with primitives, you need to create an Class which has that primitives as fields and change them via object.

KunLun
  • 3,109
  • 3
  • 18
  • 65