public class Number {
private int j;
public Number(){
j = 3;
}
public Number(int m){
j = m;
}
public void SetNum(int n){
j = n;
}
public int GetNum(){
return j;
}
}
/// (different file, same directory)
public class User {
private Number jim;
public User(){
this.jim = new Number();
}
public static void main(String []args){
User keith = new User();
User justin = new User();
??????????????????????????
}
}
I want keith.jim = justin.jim
and justin.jim = keith.jim
. Such that if i do keith.jim.SetNum(34)
, both keith
and justin's
jim.j
will be 34
. How to do that? This idea will be implement in a bigger piece of code.
Also, user.java
and Number
.java must exist. The context cannot be changed,I can add new methods but I cannot alter the context in Number
(E.G put j in user instead of Number). Each user must have a number object which every users is referencing to as well.
Others have suggested creating just one User
object. An alternative would be to have two User
objects, but with the same reference for the value of the jim
field:
User keith = new User();
User justin = new User();
justin.jim = keith.jim;
This would be useful if you have other fields where keith
and justin
need to be different, but any change in the object that the value of the jim
field refers to must be seen by both.
Both of these are valid options, depending on your requirements.
A few points, however:
This means the original value of justin.jim
because pointless; you could consider adding a User
constructor taking a Number
reference for the initial value of the field, allowing you to write:
User justin = new User(keith.jim);
Number
class to be something that isn't in java.lang
(or java.util
etc, if possible).getValue
and setValue
, personally.See more on this question at Stackoverflow