Java - Classes & Objects

Classes & Objects

Class Anatomy

package com.example.model;

public class Person {
  // fields (state)
  private final String name;       // immutable once set
  private int age;                  // mutable

  // constructors
  public Person(String name, int age) {
    this.name = name;
    this.age = age;
  }

  // methods (behavior)
  public String getName() { return name; }
  public int getAge() { return age; }
  public void birthday() { age++; }

  @Override public String toString() { return name + "(" + age + ")"; }
}

Creating Objects

Person p = new Person("Ada", 36);
p.birthday();
System.out.println(p); // Ada(37)

this, static, and instance members

  • this refers to the current instance.
  • static fields/methods belong to the class, not instances.
class MathUtil {
  static int add(int a, int b) { return a + b; }
}
int s = MathUtil.add(2,3);

equals, hashCode, toString

Override consistently to establish value semantics and useful logging.

public final class Point {
  private final int x, y;
  public Point(int x, int y) { this.x = x; this.y = y; }
  @Override public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof Point)) return false;
    Point p = (Point) o; return x == p.x && y == p.y;
  }
  @Override public int hashCode() { return java.util.Objects.hash(x,y); }
  @Override public String toString() { return "("+x+","+y+")"; }
}

Initialization Order

  • Field initializers → instance init blocks → constructor body.
  • Static fields/static init blocks run once when class is loaded.
Avoid heavy work in constructors; prefer factory methods if construction can fail or requires validation.

Try it

  1. Add equals, hashCode, and toString to a simple Point class and test behavior in a HashSet.
  2. Create a factory method Person.of(name, age) and discuss pros/cons vs constructor.