Java 可以在一条语句中修改多个对象吗?
与此相反:Java 可以在一条语句中修改多个对象吗?,java,Java,与此相反: UserProfile user1 = new UserProfile(); UserProfile user2 = new UserProfile(); UserProfile user3 = new UserProfile(); UserProfile user4 = new UserProfile(); user1.setPhoneNumber = "0001"; user2.setPhoneNumber = "0001"; user3
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";
有没有一种方法可以让我这样做,而不是为每个用户重复代码
UserProfile user1 = new UserProfile();
UserProfile user2 = new UserProfile();
UserProfile user3 = new UserProfile();
UserProfile user4 = new UserProfile();
user.setPhoneNumber = "0001";
这应该在一个循环中完成 因此,您可以声明一个
UserProfile
对象数组,然后填充它并在循环中调用setPhoneNumber
,而不是一次实例化一个对象。比如:
UserProfile[] profiles = new UserProfile[4];
for (int i = 0; i < profiles.length; i++) {
profiles[i] = new UserProfile();
profiles[i].setPhoneNumber("0001");
}
UserProfile[]profiles=新的UserProfile[4];
对于(int i=0;i
您应该根据您的需求使用静态
变量
静态变量可用于引用所有属性的公共属性
对象(并非每个对象都是唯一的),例如
员工的公司名称、学生的学校名称等
示例:
//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();
}
}
111 Karan ITS
222 Aryan ITS
输出:
//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();
}
}
111 Karan ITS
222 Aryan ITS
如果所有的用户配置文件都有相同的电话号码,那么您可以使用静态成员 如果您希望每个实例具有不同的值,但仍有一种方法可以同时设置所有值,那么您有几个选项:
Java中的数组仍然具有固定的容量。它们是静态的数据结构。也许fixed这个词用错了,我会更新我的答案。直接的答案是不行。您需要为每个对象执行单独的赋值语句(或setter调用)。有多种方法可以避免重复的代码,但最终每个对象的字段都需要单独更新。。。假设该字段是实例字段。