Grade 11 Computer Science · Writing a class
Fields, a constructor, and the object’s own name
The familiar idea, in a spelling that enforces it.
An assignment that assigned nothing
The constructor says name = name, the program passes the check and runs, and yet every student’s name comes out empty. The problem is not in that line and not in the parameter — one word is missing that you never needed in Python.
In grade ten you learned what an object is, what a constructor does, and why every field gets a value at once. All of that stays true word for word. What is added is that the language demands it rather than recommending it, and adds one small tool solving a problem that did not exist in Python.
public class Student {
private String name; // fields
private int[] grades;
public Student(String name) { // constructor
this.name = name; // field = parameter
this.grades = new int[0]; // every field, always
}
public String getName() { return this.name; }
}Why the language demands rather than recommends
In Python you could add a field to an object at any moment, even after creation. In Java the list of fields is settled in the class and does not change — every field is declared, and no new one can be added at run time. That sounds rigid, and it is exactly what lets the checking stage catch a typo in a field name before running. The rigidity is not a punishment; it is the condition for the check being able to help.
| The part | What it does |
|---|---|
| Fields | What the object holds |
| A constructor | Fills them all at creation |
| Methods | What can be done |
Example 1 — why the marking is needed
- The parameter and the field share a name.
- Without the marking, both are the parameter.
- And the assignment does nothing.
Example 2 — why the rigidity helps
- The list of fields is known in advance.
- A typo in a field name is caught.
- Before a line is run.