java - How to make object referencing to the same thing? -
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 , justin.jim = keith.jim. such if keith.jim.setnum(34), both keith , justin's jim.j 34. how that? idea implement in bigger piece of code.
also, user.java , number.java must exist. context cannot changed,i can add new methods cannot alter context in number (e.g put j in user instead of number). each user must have number object every users referencing well.
others have suggested creating 1 user object. alternative have 2 user objects, same reference value of jim field:
user keith = new user(); user justin = new user(); justin.jim = keith.jim; this useful if have other fields keith , justin need different, change in object value of jim field refers must seen both.
both of these valid options, depending on requirements.
a few points, however:
this means original value of
justin.jimbecause pointless; consider addinguserconstructor takingnumberreference initial value of field, allowing write:user justin = new user(keith.jim);- shared mutable state can become tricky reason about, particularly in face of multiple threads
- as noted in comments, should rename
numberclass isn't injava.lang(orjava.utiletc, if possible). - you should follow java naming conventions methods, using camelcase instead of pascalcase - i'd call them
getvalue,setvalue, personally.
Comments
Post a Comment