Class Creation
What you must know
A class defines instance variables (private, per object), a constructor (same name as the class, no return type, initializes state), and methods (accessors and mutators). Understand encapsulation: private fields with public accessor/mutator methods. Know how to write and call constructors, including overloaded constructors and the this keyword to distinguish parameters from fields. Understand static members (belong to the class, shared) versus instance members. Know method overloading (same name, different parameter lists) versus overriding. Be able to trace object state through a sequence of method calls, including methods that call other methods of the same object.
Traps
- A constructor has no return type-writing
voidmakes it a method, not a constructor. - Forgetting to initialize instance variables; object references default to
null, numbers to0, booleans tofalse. - Calling a static method through an instance or accessing an instance field from a static context.
- Confusing overloading (compile-time, parameter types) with overriding (runtime, subclass).
- Not tracking state changes when a mutator is called multiple times.
Rule of thumb
To trace an object, keep a small table listing each instance variable and update it after every mutator call, in execution order.
Worked example: A Counter with field count and increment() that adds 1: calling increment() three times leaves count == 3; a constructor setting count = 0 ensures a predictable start.