Shaydoth Shaydoth - 4 months ago 8
Java Question

Referencing a class object in java

Lets say I have a class User:

public class User {
String userID;
String password;
Integer connectID;
String name;

public User(String Name, String ID, String Pass, Integer connect) {
userID = ID;
password = Pass;
connectID = connect;
name = Name;
}

public String getUserID() {
return userID;
}

public String getPassword() {
return password;
}

public Integer getConnectID() {
return connectID;
}

public String getName() {
return name;
}
}


And I have a section of my code which takes the connectID of a certain object and puts it into a varaible
connectionID = (accounts.get(i)).getConnectID();
where
accounts
is an ArrayList holding all of the objects created. Would there be a way for me to use the
connectionID
variable to relate back to the object again in another method
textWindow.append("localhost." + ... + getDateTime() + " > ");
where the
...
part is the part that I want to use the
getConnectID()
method on.

Answer

Don't store connectionID as a variable. It is already stored within the User object. Instead, store the User as a variable so it's contents can be accessed again later:

//Before the for loop, in a wider scope, declare the User:
User user;
//Then, in the for loop, initialize it:
user = accounts.get(i);
//As it was declared outside the for loop, it can be accessed later:
textWindow.append("localhost." + "User ID: " + user.getConnectionID() + " at " + getDateTime() + " > ");//or however you wish to format it
Comments