Working with Methods and Encapsulation
Working with Methods and Encapsulation
This domain checks method declarations, overloading, parameter passing, constructors, access modifiers, and encapsulation. The exam expects you to distinguish compile-time signature rules from runtime behavior.
Methods and overloading
- A method declaration needs a return type, name, parameter list, and body (or
abstract). A method signature is the name plus parameter types; return type, access modifier, andthrowsclause do not count. - Overloading requires a different parameter list. Calls are resolved at compile time using widening before boxing, and boxing before varargs.
- Java is pass-by-value. Primitives pass copies; object references pass copies of the reference, so a method can mutate the object but cannot reassign the caller's variable.
- A constructor has no return type and shares the class name.
this(...)orsuper(...)must be the first statement. The compiler supplies a no-arg constructor only when no constructor is declared.
Encapsulation and access
Private fields with public getters/setters protect invariants. Access levels: private (class only), package-private (same package), protected (same package plus subclasses), and public (everywhere). static members belong to the class; instance members require an object. final variables cannot be reassigned.
Worked example
class Counter {
private int count;
public void add(int count) {
count = count + 1;
}
public int getCount() { return count; }
}
The parameter count shadows the field. add increments the parameter, not the field, so getCount() still returns 0. Use this.count to reach the field.
Traps
- Changing only the return type is not overloading; it is a compile error.
- A static method cannot use
thisor directly access instance fields. - A private method is not overridden, so calls may bind to the parent version.
- Varargs must be last and there can be only one.
this()andsuper()cannot both appear, and neither can appear outside a constructor's first statement.