Indirect object access in JAVA

I am trying to understand how to indirectly access objects.

Using the following simple Customer Class. For example, here are two of 50 Customer objects. They are Bill and Bob.

public class Customer {
private int CustNum;
private String name;
private String homePhone;

Customer Bill = new Customer(100, “Bill West”,“1234567890”);
Customer Bob = new Customer(101, “Bob East”,“1234567891”);

I then wish to perform tasks on a certain object.
i.e. I want to work on object “Bob”

String custObj= “Bob”;

int dummynum = &custObj.CustNum;

I would like dummynum to contain the value 101.

You could even extend this to

String custObj= “Bob”;
String custField= “CustNum”;

int dummynum = &custObj.&custField;

The thought is to create dynamic flexible methods.

Pretty sure you cant do this.
You could put them all in a map though.
EDIT: Also, stackoverflow for this kinda shit man, seriously :stuck_out_tongue:

You can create another Customer, use it to point to a specific Customer, then invoke a method on your container Customer, which now “contains” the Customer object instance.

private Customer bob = new Customer(stuff, stuff, stuff);
private Customer john = new Customer(stuff, stuff, stuff);

private Customer myCustomer;

// Let's do Bob first
myCustomer = bob;
myCustomer.doStuff();                   // Equivalent to "bob.doStuff();"

int myInt = myCustomer.getCustNum();    /* Equivalent to "int myInt = bob.getCustNum();"
                                         * Notice how I am not trying to access the custNum variable directly.
                                         * Instead, I am calling a "getter" int method defined in the Customer
                                         * class that returns the private variable custNum.
                                         * Most of the time this is considered to be good coding practice.
                                         */

// Now let's do John
myCustomer = john;
myCustomer.doStuff();                   // Equivalent to "john.doStuff();"

EDIT: By the way, try not to capitalize your instance names… it’s bad practice and can be confusing. See the standard Java coding conventions for more. :wink:

Sorry, I took them from the actual problem, but will review the conventions.
I will also look at your suggestion.

I updated/clarified some of my code comments in case you’re interested.

And since you’re handling a large number of Customer objects, I suggest handling them using an array instead of repeatedly making new objects.

Founded in 2004, Leakfree.org became one of the first online communities dedicated to Valve’s Source engine development. It is more famously known for the formation of Black Mesa: Source under the 'Leakfree Modification Team' handle in September 2004.