MJ DLS
MJ DLS

Reputation: 99

Can you modify multiple objects in one statement?

Instead of this:

UserProfile user1 = new UserProfile();
UserProfile user2 = new UserProfile();
UserProfile user3 = new UserProfile();
UserProfile user4 = new UserProfile();

user1.setPhoneNumber = "0001";
user2.setPhoneNumber = "0001";
user3.setPhoneNumber = "0001";
user4.setPhoneNumber = "0001";

Is there a way that I could just do this instead of repeating the code for every user?

UserProfile user1 = new UserProfile(); 
UserProfile user2 = new UserProfile(); 
UserProfile user3 = new UserProfile(); 
UserProfile user4 = new UserProfile();
user.setPhoneNumber = "0001";

Upvotes: 2

Views: 536

Answers (3)

Sathiamoorthy
Sathiamoorthy

Reputation: 11580

You should use static variable for your requirement.

The static variable can be used to refer to the common property of all objects (which is not unique for each object), for example, the company name of employees, college name of students, etc.

Example:

//Java Program to demonstrate the use of static variable 
class Student{  
   int rollno;//instance variable  
   String name;  
   static String college ="ITS";//static variable  
   //constructor  
   Student(int r, String n){  
      rollno = r;  
      name = n;  
   }  
   //method to display the values  
   void display (){System.out.println(rollno+" "+name+" "+college);}  
}  

//Test class to show the values of objects  
public class TestStaticVariable1{  
   public static void main(String args[]){  
      Student s1 = new Student(111,"Karan");  
      Student s2 = new Student(222,"Aryan");  
      //we can change the college of all objects by the single line of code  
      //Student.college="BBDIT";  
      s1.display();  
      s2.display();  
   }  
} 

Output:

111 Karan ITS
222 Aryan ITS

Upvotes: 0

John3136
John3136

Reputation: 29266

If all of the UserProfiles always have the same phone number then you could use a static member.

If you want each instance to have different values but still have a way to set them all at once then you have a few options:

  1. Keep a collection of all UserProfiles (e.g. a vector) and call setPhoneNumber() for each one.

  2. Have a static phone number and a class instance member. method setAllPhoneNumbers() sets the static value. setPhoneNumber() sets the instance value. getPhoneNumber() returns the instance (if set) else the static

  3. Implement a "setAllPhoneNumbers" using reflection.

Upvotes: 0

Henry Twist
Henry Twist

Reputation: 5980

This should be done within a loop.

So instead of instantiating your objects one at a time you could declare an array of UserProfile objects, then populate it and call setPhoneNumber within the loop. So something like:

UserProfile[] profiles = new UserProfile[4];

for (int i = 0; i < profiles.length; i++) {
    profiles[i] = new UserProfile();
    profiles[i].setPhoneNumber("0001");
}

Upvotes: 1

Related Questions