Implement a class Class
with the following attributes and methods:
- A public attribute
students
which is a array ofStudent
instances. - A constructor with a parameter n, which is the total number of students in this class. The constructor should create n Student instances and initialized with student id from 0 ~ n-1
Example
Example 1:
Input: 3Output: [0, 1, 2]Explanation: For 3 students, your cls.students[0] should equal to 0, cls.students[1] should equal to 1 and the cls.students[2] should equal to 2.
Example 2:
Input: 5Output: [0, 1, 2, 3, 4]
注意:
- :数组声明不能制定大小(因为只是创建了一个引用变量),数组创建时必须制定大小!
- Class类:先声明一个数组类型的引用变量,在构造方法中才能使引用变量指向创建的数组,因为有了参数n,知道数组长度后,才能创建数组。
代码:
class Student { public int id; public Student(int id) { this.id = id; }}public class Class { public Student[] students; // 声明Student类型数组,即创建一个引用 public Class(int n) { this.students = new Student[n]; // 创建Student类型数组,将引用(students)指向此数组 for (int i = 0; i < n; i++) { students[i] = new Student(i); } }}