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.

What is visible is the opening; what is private sits inside and is unreachable.
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 partWhat it does
FieldsWhat the object holds
A constructorFills them all at creation
MethodsWhat can be done

Example 1 — why the marking is needed

  1. The parameter and the field share a name.
  2. Without the marking, both are the parameter.
  3. And the assignment does nothing.

Example 2 — why the rigidity helps

  1. The list of fields is known in advance.
  2. A typo in a field name is caught.
  3. Before a line is run.
Had line 6 been name = name, the parameter would be assigned to itself, the field would stay null — and the output would be null.