共計 742 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 Java 中,可以使用循環結構和數組來一次性創建多個對象。具體步驟如下:
- 定義一個類,用于創建對象。例如,創建一個名為 Student 的類。
public class Student {
private String name;
private int age;
// 構造方法
public Student(String name, int age) {
this.name = name;
this.age = age;
}
// getter 和 setter 方法
public String getName() {return name;}
public void setName(String name) {this.name = name;}
public int getAge() {return age;}
public void setAge(int age) {this.age = age;}
}
- 在主類中使用循環結構和數組來一次性創建多個對象。例如,創建 3 個學生對象。
public class Main {public static void main(String[] args) {
// 定義一個長度為 3 的 Student 數組
Student[] students = new Student[3];
// 使用循環結構創建多個對象
for (int i = 0; i < students.length; i++) {students[i] = new Student(" 學生 " + (i + 1), i + 10);
}
// 打印每個學生對象的信息
for (Student student : students) {System.out.println(" 姓名:" + student.getName() + ",年齡:" + student.getAge());
}
}
}
執行上述代碼,將會創建 3 個學生對象,并打印每個學生對象的信息。
丸趣 TV 網 – 提供最優質的資源集合!
正文完