Student ID

这是一道男默女泪的初始简单题。考察的是array object field的定义和初始化。

Q:

Implement a class Class with the following attributes and methods:

A public attribute students which is a array of Student 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
Class cls = new Class(3)
cls.students[0]; // should be a student instance with id = 0
cls.students[1]; // should be a student instance with id = 1
cls.students[2]; // should be a student instance with id = 2

代码如下

参考网站:http://stackoverflow.com/questions/5889034/how-to-initialize-an-array-of-objects-in-java

class Student {
    public int id;

    public Student(int id) {
        this.id = id;
    }
}

public class Class {
    /**
     * Declare a public attribute `students` which is an array of `Student`
     * instances
     */
    // write your code here.
    public Student[] students;

    /**
     * Declare a constructor with a parameter n which is the total number of
     * students in the *class*. The constructor should create n Student
     * instances and initialized with student id from 0 ~ n-1
     */
    // write your code here
    public Class(int n) {
        students = new Student[n];
        for (int i = 0; i < n; i++) {
            students[i] = new Student(i);
            students[i].id = i;
        }
    }
}

精华:

student[i] = new Student(i);

for (int i = 0; i < n; i++) {
                students[i] = new Student(i);
                students[i].id = i;