Access data from already instantiated classes

Asked

Viewed 3,004 times

3

I need to access data contained in class variables already instantiated from other classes

User_Info info = new User_Info()

I think I would need the memory address that is the right "info"?

public class User_Info {
    private int user_id;
    private String nickname;
    private Image profile_picture;
    private String first_name;
    private String last_name;
    private String country;
    private String gender;
    private String state;
    private Date date_nasc;

    public int getUser_id() {
        return user_id;
    }
    public void setUser_id(int user_id) {
        this.user_id = user_id;
    }
    public String getNickname() {
        return nickname;
    }
    public void setNickname(String nickname) {
        this.nickname = nickname;
    }
    public Image getProfile_picture() {
        return profile_picture;
    }
    public void setProfile_picture(Image profile_picture) {
        this.profile_picture = profile_picture;
    }
    public String getFirst_name() {
        return first_name;
    }
    public void setFirst_name(String first_name) {
        this.first_name = first_name;
    }
    public String getLast_name() {
        return last_name;
    }
    public void setLast_name(String last_name) {
        this.last_name = last_name;
    }
    public String getCountry() {
        return country;
    }
    public void setCountry(String country) {
        this.country = country;
    }
    public String getGender() {
        return gender;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }
    public String getState() {
        return state;
    }
    public void setState(String state) {
        this.state = state;
    }
    public Date getDate_nasc() {
        return date_nasc;
    }
    public void setDate_nasc(Date date_nasc) {
        this.date_nasc = date_nasc;
    }
}
  • post the User_info.java code

  • don’t need the code...

  • You definitely don’t need the memory address of info. I asked for your code so that it is possible to know more details and suddenly better direct the answer to your question.

  • 1

    this there , I urge this at the beginning of the program but in the course of time I need to change these values in other classes , how will I access these data that are already in memory?

  • @Lucasbertollo come on, if you can put example 1 at least of the other classes too, please ?

  • @Harrypotter looks at the comments in my reply, he wants a shared reference of the same class in several other classes, or maybe define the attributes statically.

  • Thanks @Math, got it let’s see the unwind rs

  • @Math THAT.. could you tell me more about this shared reference?

  • @Math he doesn’t want Singleton?

  • 1

    @Harrypotter also, are 3 options

  • @Math would like to know the 3 ahaha

Show 6 more comments

3 answers

4


Considering another supposed class called Usandouserinfo.java, which is in the same package as your User_info class, do:

public class UsandoUserInfo {
    public static void main(String[] args) {
        User_Info info = new User_Info();
        info.setUser_id(44); //definiu o valor da variável user_id como sendo 44
        System.out.println(info.getUser_id()); //pegou o valor e imprimiu 44 no seu console
    }
}

Ready, you used the get and set of your User_info class to set and take the value of user_id

However, if you want to change the same attribute of your User_info class from another class you have some alternatives, let’s see:

1) Share reference stored by reference variable info with their other classes

You can create a reference and by calling other classes you pass this reference to them, example:

Usandouserinfo.java

public class UsandoUserInfo {
    public static void main(String[] args) {
        User_Info info = new User_Info();
        info.setUser_id(44);
        System.out.println("Valor atribuido pelo UsandoUserInfo: " + info.getUser_id());

        UsandoUserInfo2 u2 = new UsandoUserInfo2(info);
        u2.atribuiUserId();
        System.out.println("Valor atribuido pelo UsandoUserInfo2: " + info.getUser_id());
    }
}

Using Userinfo2.java

public class UsandoUserInfo2 {
    private User_Info info;
    public UsandoUserInfo2(User_Info info) {
        this.info = info;
    }
    public void atribuiUserId(){
        info.setUser_id(55);
    }
}

Upshot:

Value assigned by Usandouserinfo: 44
Value assigned by Usandouserinfo2: 55

2) Make your User_info class a Singleton

Probably the most correct and bug-free, here you make use of the Singleton project standard, which is a way to ensure that there will never be more than one instance of your class in the same JVM.

To apply this pattern you need to basically define a private constructor in your User_info class and control its access. That is, only those who will call this builder is the class itself. So you guarantee that you will only create a single instance of it, which is when the reference variable is null, after that you return the already created variable instead of creating a new one.

To provide this reference created by your own class you must make a static method that makes it available.

Example:

public class User_Info {
    private int user_id;
    private String nickname;
    private static User_Info info;

    private User_Info() {
    }

    public static User_Info getInstance() {
        if(info == null) {
            info = new User_Info();         
        }
        return info;
    }

    public int getUser_id() {
        return user_id;
    }
    public void setUser_id(int user_id) {
        this.user_id = user_id;
    }
    public String getNickname() {
        return nickname;
    }
    public void setNickname(String nickname) {
        this.nickname = nickname;
    }
}

Usandouserinfo.java

public class UsandoUserInfo {
    public static void main(String[] args) {
        User_Info info = User_Info.getInstance();
        info.setUser_id(44);
        System.out.println("Valor atribuido pelo UsandoUserInfo: " + info.getUser_id());

        UsandoUserInfo2 u2 = new UsandoUserInfo2();
        u2.atribuiUserId();
        System.out.println("Valor atribuido pelo UsandoUserInfo2: " + info.getUser_id());
    }
}

Using Userinfo2.java

public class UsandoUserInfo2 {
    private User_Info info;

    public UsandoUserInfo2() {
        info = User_Info.getInstance();
    }

    public void atribuiUserId(){
        info.setUser_id(55);
    }
}

Upshot:

Value assigned by Usandouserinfo: 44
Value assigned by Usandouserinfo2: 55

3) Set your User_info class variables to be static.

Define as static It is easier however I believe that it is the worst of the options, because it hurts the principle of encapsulation. As I do not know for what you need, it does not cost to show the possibildiade:

User_info.java

public class User_Info {
    public static int user_id;
    public static String nickname;
}

Usandouserinfo.java

public class UsandoUserInfo {
    public static void main(String[] args) {
        User_Info.user_id = 44;
        System.out.println("Valor atribuido pelo UsandoUserInfo: " + User_Info.user_id);

        UsandoUserInfo2 u2 = new UsandoUserInfo2();
        u2.atribuiUserId();
        System.out.println("Valor atribuido pelo UsandoUserInfo2: " + User_Info.user_id);
    }
}

Using Userinfo2.java

public class UsandoUserInfo2 {
    public void atribuiUserId(){
        User_Info.user_id = 55;
    }
}

Upshot:

Value assigned by Usandouserinfo: 44
Value assigned by Usandouserinfo2: 55

  • ok.. now I also want to access from the Usandouserinfo2 class as it does?

  • @Lucasbertollo do you want to access exactly the value that was set in this class? For example, the 44?

  • this and change to 55 for example , but of the class Usandouserinfo2

  • 1

    @Lucasbertollo the 3 options I can imagine :)

2

Utilize getter / setters as for example, in a dummy variable minhaString defined within its User_info class:

public class User_Info {

   private minhaString;

   public String getMinhaString(){
     return minhaString;
   }

   public void setMinhaString(String str){
      minhaString = str;
   }
}

And then to access:

User_Info info = new User_Info()
info.setMinhaString("uma String");
String s = info.getMinhaString();
//s terá o valor de "uma String"

Or set the variable to public:

User_Info info = new User_Info()
info.minhaString = "uma String";
  • That I know I don’t think anybody’s trying to understand me... okay.. Let’s assume I’ve entered this on Main now I need to change this data from the Altered Data class as I will access?

  • Lucas, you have to pass your object info as a reference... simple as that, ex: AlteraDados ad = new AlteraDados(info); or by creating any method: AlteraDados ad = new AlteraDados(); ad.alteraValor(info); got it ?

  • Would not have to take the memory address that this object? to be able to use any part of the program? because other classes could not see "info" right?

0

Your class User_info certainly has attributes and these attributes are encapsulated in getters and setters, correct?

To access the attribute data just call the getters. For example:

User_Info info = new User_Info();
info.setCodigo(1); // atribuirá o número '1' ao atributo 'codigo', supondo que seja um atributo do tipo int/Integer
System.out.println(info.getCodigo()); // imprimirá no console o que estiver guardado no atributo 'codigo'
  • right but to access her from another class?

  • If User_info is a static attribute, you can access from another class without problems, just invoke the getters. You need to better detail what you have done so far, what you intend to do, what the purpose of the system, what the purpose of User_info, where it will be used, why, when, how, etc...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.