2 · 32 · 5 min
Classes, objects and what static really means
A class is a description. An object is a thing built from it. The class Student is written once; there are 1,200 student objects.
class Student {
static int total = 0; // one copy, shared by the class
int rollNo; // one copy per object
Student(int rollNo) {
this.rollNo = rollNo;
total++;
}
}Static versus instance
total belongs to the class. It exists before any object does, there is exactly one, and every constructor increments the same one.
rollNo belongs to the object. Each student has their own.
new Student(41);
new Student(92);
System.out.println(Student.total); // 2Construction order
class A { A() { System.out.print("A"); } }
class B extends A { B() { System.out.print("B"); } }
new B(); // prints ABEvery constructor begins with a call to its parent's, inserted by the compiler as super() if you do not write one. So the parent's body runs first, all the way up the chain, and the subclass's body runs last.
The reason is that a subclass may use inherited fields, and those must be initialised before its own code can rely on them. Construction runs top down.