Grade 11 Computer Science · The bridge to Java
Everything lives inside a class
How a program starts when no code floats in a file.
How do you start when nothing exists yet?
If every operation must belong to something, someone has to create that something before the program starts. But creating it is already an operation. The way out of that circle is one word in the code — and it is also the reason for the first error nearly everyone meets.
In Python one can write a line in a file and it will run. In Java that is impossible — every line belongs to a class, and every operation belongs to a class. That raises an immediate question: if no line stands alone, where does the program start?
public class Report {
static int doubled(int n) { // belongs to the class
return n * 2;
}
public static void main(String[] args) {
System.out.println(doubled(21)); // no object needed
}
}When it belongs to the class and when to the object
The rule is simple and worth adopting at once: an operation belongs to an object if it touches a particular object’s data, and to the class if it does not. An operation that doubles a number needs no object — it takes a number and returns a number. An operation computing a particular student’s average does. This is exactly the question you asked in the objects unit in grade ten, and now it has an explicit marking in the language.
| Belongs to… | When | Requires an object |
|---|---|---|
| The class | It does not touch an object’s data | No |
| The object | It touches a particular one’s data | Yes |
Example 1 — why the entry point belongs to the class
- At the start there are no objects yet.
- So an object’s operation cannot be called.
- It must be available from the class.
Example 2 — how a new operation is decided
- Ask whether it touches an object’s data.
- If not — it belongs to the class.
- If so — it belongs to the object.