Objects, Classes & OOP Design
Classes & Objects
A class is a blueprint: state (fields) plus behavior (methods) behind an access-controlled boundary. Objects are created with
new, live on the heap, and are always handled through references.- Object variables are references — assignment aliases, it never copies the object
- Encapsulation: private fields + public methods define a stable contract
- Access levels:
private→ package-private (default) →protected→public - Method parameters are passed by value — including reference values
- Getters must not leak references to mutable internals
public class Employee {
private String name;
private double salary;
public Employee(String name, double salary) {
this.name = name;
this.salary = salary;
}
public String getName() { return name; }
public double getSalary() { return salary; }
public void raiseSalary(double byPercent) {
salary += salary * byPercent / 100;
}
}Encapsulation is the whole game: fields stay private, and the public methods form a contract you can keep while freely changing the representation. Effective Java Item 15 ("minimize accessibility") and Item 16 ("use accessor methods, not public fields") are the two rules that make evolution possible.
References, aliasing, and parameter passing
void raise(Employee e) { e.raiseSalary(10); } // works: e is a COPY of the reference,
// but both copies point to the same object
void swap(Employee a, Employee b) {
Employee tmp = a; a = b; b = tmp; // useless: swaps local copies only
}A method receives copies of its arguments. For objects, the copy is the reference, so methods can mutate the object it points to — but can never make the caller's variable point elsewhere. "Java is pass-by-reference" is the most persistent falsehood in Java folklore.