Skip to content
notes.vinhnq.com

Search

OOP & DesignJunior18 min read

Object-oriented programming: classes, objects, constructors, static and access modifiers

Review 11 cards
On this page

Object-oriented programming series: 1. Classes, objects, access modifiers · 2. Immutability, equals/hashCode, final · 3. Inheritance, encapsulation, polymorphism · 4. Abstract classes and interfaces · 5. UML, class relationships · 6. Wrappers, BigDecimal, String

A real backend has hundreds of business concepts (orders, customers, payments…); scatter the data and logic and fixing one thing breaks three others. Object-oriented programming (OOP) puts related data and behavior together in an object and draws clear boundaries between parts. This post is the foundation: classes, objects, constructors, static, packages and access modifiers; you only need the syntax from Java basics.

The rest of the series: immutable objects, equals/hashCode and final in part 2; inheritance, encapsulation and polymorphism in part 3; abstraction and initialization order in part 4; UML and class relationships in part 5; wrappers, BigDecimal and String in part 6.

1. Objects and classes

Key idea: a class is the blueprint (fields + methods); an object is a concrete entity created from it with new. Every object is an instance of its class.

An object has three things:

  • State: fields. An animal has a name, an age, a weight.
  • Behavior: methods. An animal eats, makes sounds, sleeps.
  • Identity: two dogs with the same name and age are still two different objects. The slides skip this, but it is exactly why == and equals differ.

One mold can produce millions of buns; one class can create as many objects as you like.

class Animal {
    String name;          // field: state
    int age;

    void eat() {          // method: behavior
        System.out.println(name + " is eating");
    }
}

The slides say “everything in Java lives inside a class”. More precisely, all code lives inside a type: a class, interface, enum or record. Since Java 25, compact source files let you write void main() without declaring a class, but the compiler still generates one behind the scenes.

Constructors

Key idea: a constructor is a special “method” used only to initialize an object: it has the class’s name, no return type, and only runs through new. Its job is to make the object valid from birth.

  • No return type, not even void. Write void Animal() and you get an ordinary method, not a constructor, a nasty bug to spot.
  • It only runs through new, or through this(...)/super(...) from another constructor.
class Animal {
    private final String name;
    private int age;

    Animal(String name) {             // overloaded constructor
        this(name, 0);                // delegate to another constructor: constructor chaining
    }

    Animal(String name, int age) {
        if (age < 0) throw new IllegalArgumentException("age must be >= 0");
        this.name = name;             // this.name is the field, name is the parameter
        this.age = age;
    }

    void showInfo() {
        System.out.printf("Name: %s - Age: %d%n", name, age);
    }
}

Animal dog = new Animal("Rex", 2);    // declare + create
Animal cat;                           // declared only; cat doesn't point anywhere yet
cat = new Animal("Tom");              // create later
dog.showInfo();                       // access members with the dot operator
  • this tells a field apart from a parameter with the same name.
  • A class can have several constructors with different parameter lists. One constructor calling another through this(...) is constructor chaining: validation lives in one place.
  • If you write no constructor, the compiler adds a no-arg default constructor. Write any constructor and it disappears, which bites people when JPA or Jackson needs a no-arg constructor.
  • An invariant is a rule that must always hold (say, age ≥ 0). The constructor enforces it; don’t let an object exist half-built while you hope someone calls the right setters.

What new does, in order: allocate memory on the heap (where objects live), set fields to their defaults, run initializer blocks and super(...), run the constructor body, and return the reference.

2. static: belongs to the class, not to an object

Key idea: a static member has exactly one copy, shared by every instance, and has no this. Use it when a value or behavior doesn’t depend on the state of a particular object.

flowchart TB
  C["class Animal<br/>static int count = 3"]
  A1["dog1<br/>name=Rex"]
  A2["dog2<br/>name=Max"]
  A3["dog3<br/>name=Spot"]
  A1 -. shared .-> C
  A2 -. shared .-> C
  A3 -. shared .-> C
  • Access a static variable as ClassName.variable; call a static method as ClassName.method().
  • A static method can’t touch instance fields.
  • Static members take access modifiers like any other member.

The slides increment Animal.count++ from outside after each new: easy to forget, and it leaks an internal detail. Let the class count itself in the constructor:

class Animal {
    private static int count = 0;
    private final String name;

    Animal(String name) {
        this.name = name;
        count++;                      // not thread-safe; see the senior section below
    }

    static int count() { return count; }
}

The slides’ example is static double perimeter(Circle c), which takes a circle as a parameter. It works, but the object-oriented version lets the circle compute its own: circle.perimeter(), which is what encapsulation in part 3 is about. Also prefer Math.PI over 3.14.

3. Packages and imports

Key idea: a package is a folder that groups related classes and creates a namespace, so two classes with the same name in different packages don’t clash (java.util.Date versus java.sql.Date). To use a class from another package, import it.

// File: src/main/java/com/vinhnq/shape/Circle.java
package com.vinhnq.shape;

public class Circle { ... }
// A file in another package
package com.vinhnq.app;

import com.vinhnq.shape.Circle;       // import one class
import java.util.*;                   // import a whole package (not its subpackages)

public class App {
    Circle c = new Circle(2);
}
  • Classes in the same package use each other without importing. java.lang (String, Math…) is always imported.
  • Package names: lowercase, reversed domain (com.company.project.module). The slides use a capitalized Shape package, which breaks the convention.
File rules and import static
  • The package statement must be the first statement in the file (only comments may come before it). Each file belongs to exactly one package.
  • The directory must match the package name: com.vinhnq.shape.Circle lives at .../com/vinhnq/shape/Circle.java. The compiler and IDE rely on that convention to find classes.
  • import static imports static members so you can use them without the class name: import static java.lang.Math.PI; then PI * r * r. It suits constants and test assertions (assertThat(...)); overuse it and readers can’t tell where a method comes from.

4. Access modifiers

Key idea: access modifiers decide who can see a field, method or constructor. Start with the narrowest level (private) and widen only when you have to, because anything public becomes a contract with the outside world.

Modifier Same class Same package Subclass in another package Everywhere
private ✓
(default, package-private) ✓ ✓
protected ✓ ✓ ✓
public ✓ ✓ ✓ ✓
  • A top-level class can only be public or package-private; nested classes (classes declared inside another class) can use all four.
  • A private method can only be called from inside the class that declares it. (The method slide says “the class that defines the attribute”, a copy-paste slip from the attribute slide.)
  • Changing something public raises backward-compatibility concerns.
  • Since Java 9, the module system (module-info.java) adds another layer: a public class in a package that isn’t exports-ed is still invisible to other modules.

Exercises

Each prompt is a short paraphrase. All solutions were run on JDK 21.

1. A Circle class with a radius, perimeter and area

public final class Circle {
    private final double radius;

    public Circle(double radius) {
        if (radius < 0) throw new IllegalArgumentException("radius must be >= 0");
        this.radius = radius;
    }

    public double perimeter() { return 2 * Math.PI * radius; }
    public double area() { return Math.PI * radius * radius; }

    public static void main(String[] args) {
        Circle c = new Circle(5.5);
        System.out.printf("Perimeter: %.2f, area: %.2f%n", c.perimeter(), c.area()); // 34.56, 95.03
    }
}

Behavior lives in the object (encapsulation), the object is immutable, and input is validated in the constructor.

2. A Student class

Requirements: a student has a full name, address, email, phone number and an alphanumeric student code; can attend class, do homework, pay tuition, take exams and print their details; has constructors with and without parameters, plus getters and setters. Create a few students and call those actions.

Solution 2: the Student class
public class Student {
    private static final Pattern CODE = Pattern.compile("[A-Z]\\d{2}[A-Z]{4}\\d{3}");   // e.g. B22DCCN175
    private static final Pattern EMAIL = Pattern.compile("^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$");

    private String code;
    private String fullName;
    private String address;
    private String email;
    private String phone;
    private boolean tuitionPaid;

    public Student() { }    // required by the exercise; frameworks like Jackson/JPA also need it

    public Student(String code, String fullName, String address, String email, String phone) {
        setCode(code);
        setFullName(fullName);
        this.address = address;
        setEmail(email);
        this.phone = phone;
    }

    public void attendClass(String subject) { System.out.println(fullName + " attends " + subject); }
    public void doHomework(String title)    { System.out.println(fullName + " works on: " + title); }
    public void takeExam(String subject)    { System.out.println(fullName + " takes the " + subject + " exam"); }

    public void payTuition(BigDecimal amount) {
        if (amount.signum() <= 0) throw new IllegalArgumentException("Amount must be > 0");
        tuitionPaid = true;
        System.out.println(fullName + " paid " + amount);
    }

    public String getCode() { return code; }
    public void setCode(String code) {
        if (code == null || !CODE.matcher(code).matches())
            throw new IllegalArgumentException("Invalid student code: " + code);
        this.code = code;
    }
    public String getFullName() { return fullName; }
    public void setFullName(String fullName) {
        if (fullName == null || fullName.isBlank()) throw new IllegalArgumentException("Name is required");
        this.fullName = fullName.strip();
    }
    public String getEmail() { return email; }
    public void setEmail(String email) {
        if (email == null || !EMAIL.matcher(email).matches())
            throw new IllegalArgumentException("Invalid email: " + email);
        this.email = email;
    }
    public String getAddress() { return address; }
    public void setAddress(String address) { this.address = address; }
    public String getPhone() { return phone; }
    public void setPhone(String phone) { this.phone = phone; }
    public boolean isTuitionPaid() { return tuitionPaid; }   // no setter: it only changes via payTuition

    @Override public String toString() {
        return "Student[%s, %s, %s, %s, %s, tuitionPaid=%b]"
                .formatted(code, fullName, address, email, phone, tuitionPaid);
    }

    public static void main(String[] args) {
        Student s = new Student("B22DCCN175", "Nguyen Van A", "Hanoi", "a@example.com", "0900000000");
        s.attendClass("Java");
        s.doHomework("OOP");
        s.payTuition(new BigDecimal("15000000"));
        s.takeExam("Java");
        System.out.println(s);
    }
}

The exercise asks for setters on every field, but I still put validation inside them. tuitionPaid can’t be set from outside, because that state should only change through the payTuition behavior. That is real encapsulation, not just getters and setters.

3. Lab 04: an Employee class encapsulated in a model package

Task (paraphrased): create a lab04 package with two sub-packages: model holds an Employee class, the other holds main. Employee has private fields for name, age, department, salary and company; a constructor taking 4 arguments (no company), getters/setters, a method that prints the employee, and a method that raises the salary by 15% when the input is valid. In main, create two employees, print them, raise their salaries and print them again. Alongside it comes an access-modifier experiment: from another package, access a private, default, protected and public field in turn and see which lines compile.

Result of the access-modifier experiment, from Main in package lab04.app (a different package, not a subclass) accessing the fields of an Employee that declares all four levels:

Field Compiles? javac message
private String name No name has private access in Employee
int age (default) No age is not public in Employee; cannot be accessed from outside package
protected String department No department has protected access in Employee
public double salary Yes
Lab 04 solution: Employee, Main and output

Two files, compiled with javac -d out $(find src -name '*.java') and run with java -cp out lab04.app.Main.

// src/lab04/model/Employee.java
package lab04.model;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Objects;

public final class Employee {
    public static final String DEFAULT_COMPANY = "ABC Corporation";
    private static final BigDecimal HUNDRED = BigDecimal.valueOf(100);

    private String name;
    private int age;
    private String department;
    private BigDecimal salary;
    private String company;

    public Employee(String name, int age, String department, BigDecimal salary) {
        this(name, age, department, salary, DEFAULT_COMPANY);
    }

    public Employee(String name, int age, String department, BigDecimal salary, String company) {
        setName(name);
        setAge(age);
        setDepartment(department);
        if (salary == null || salary.signum() < 0) throw new IllegalArgumentException("salary must be >= 0");
        this.salary = salary;
        setCompany(company);
    }

    /** Raises the salary by a percentage, e.g. raiseSalary(15) means +15%. */
    public void raiseSalary(double percent) {
        if (percent <= 0) throw new IllegalArgumentException("percent must be > 0, got " + percent);
        BigDecimal factor = BigDecimal.ONE.add(BigDecimal.valueOf(percent).divide(HUNDRED));
        salary = salary.multiply(factor).setScale(2, RoundingMode.HALF_UP);
    }

    public void showInfo() {
        System.out.printf("Name: %s%nAge: %d%nDepartment: %s%nSalary: %s%nCompany: %s%n-------------------------%n",
                name, age, department, salary.toPlainString(), company);
    }

    public String getName() { return name; }
    public void setName(String name) {
        if (name == null || name.isBlank()) throw new IllegalArgumentException("name is required");
        this.name = name.strip();
    }
    public int getAge() { return age; }
    public void setAge(int age) {
        if (age < 18 || age > 70) throw new IllegalArgumentException("age out of range: " + age);
        this.age = age;
    }
    public String getDepartment() { return department; }
    public void setDepartment(String department) { this.department = Objects.requireNonNull(department, "department"); }
    public BigDecimal getSalary() { return salary; }   // no setSalary: the salary only changes through raiseSalary
    public String getCompany() { return company; }
    public void setCompany(String company) { this.company = Objects.requireNonNull(company, "company"); }
}
// src/lab04/app/Main.java
package lab04.app;

import java.math.BigDecimal;
import java.util.List;
import lab04.model.Employee;

public class Main {
    public static void main(String[] args) {
        List<Employee> staff = List.of(
                new Employee("Lan", 25, "Sales", new BigDecimal("8000")),
                new Employee("Minh", 30, "IT", new BigDecimal("10000")));

        System.out.println("== BEFORE RAISE ==");
        staff.forEach(Employee::showInfo);

        staff.forEach(e -> e.raiseSalary(15));

        System.out.println("== AFTER RAISE ==");
        staff.forEach(Employee::showInfo);

        try {
            staff.get(0).raiseSalary(-5);
        } catch (IllegalArgumentException ex) {
            System.out.println("Rejected: " + ex.getMessage());
        }
        // staff.get(0).name;     // compile error: name has private access in lab04.model.Employee
        // staff.get(0).salary;   // same compile error
    }
}
== BEFORE RAISE ==
Name: Lan
Age: 25
Department: Sales
Salary: 8000
Company: ABC Corporation
-------------------------
Name: Minh
Age: 30
Department: IT
Salary: 10000
Company: ABC Corporation
-------------------------
== AFTER RAISE ==
Name: Lan
...
Salary: 9200.00
...
Name: Minh
...
Salary: 11500.00
...
Rejected: percent must be > 0, got -5.0

Why it looks like this:

  • Constructor chaining for the default company: the task asks for a 4-argument constructor, but the class has 5 fields and the sample output puts everyone at “ABC Corporation”. The 4-argument constructor calls this(..., DEFAULT_COMPANY). If the value were always the same for every object it should be a static final constant; here the company may differ later, so it stays an instance field with a default.
  • Renamed parameter: the task names the method raiseSalary(double amount) yet says “raise by 15%”; the name says one thing and the behavior another. I renamed it to raiseSalary(double percent) and call it with 15. Parameter names are part of the API.
  • Invalid input throws: IllegalArgumentException instead of being silently ignored, so the caller learns about the mistake immediately.
  • No setSalary: the salary only changes through raiseSalary, which is what encapsulation actually means (see part 3). Money is a BigDecimal, rounded to 2 decimals.
  • The constructor calls the setters to reuse validation: only safe because the class is final. If a subclass could override a setter, the constructor would run the subclass’s version before the subclass is initialized (see part 4).
What a senior would also change in Lab 04
  • Derive age from a LocalDate birthDate: a stored age is wrong a year later.
  • Make the company a reference to a Company entity, not a string.
  • A raise is an audited business operation (who approved it, when, old and new amount): it belongs in a service and is stored as history, not just a field overwrite.
  • showInfo() prints straight to the console; turn it into toString() or a DTO so it can be tested.

Remember

  • Tell apart class, object and instance, and explain why identity makes == differ from equals.
  • Know when the default constructor disappears and why JPA/Jackson need a no-arg constructor.
  • Explain when to use static and why mutable static state is dangerous in Spring.
  • Redraw the four-level access table and name the two protected traps (it opens the whole package; across packages it only works through a subclass-typed reference).
  • Know why a constructor calling setters is only safe when the class is final.

Interview questions

Junior

What is the difference between a class and an object?

A class is a blueprint; an object is a concrete instance created from it with new.

The class defines fields and methods. The object has its own state on the heap. One class can produce many objects.

How does a constructor differ from a regular method? When do you get a default constructor?

A constructor has the class’s name, no return type, and runs only during object creation. The default constructor is generated only if the class declares no constructors at all.

Once you write a constructor with parameters, you must add a no-arg one yourself if you need it.

What are Java’s four access levels?

private (same class), package-private/default (same package), protected (same package plus subclasses), public (everywhere).

A top-level class can only be public or package-private.

Can a static method call an instance method directly? Why is main static?

No: a static method isn’t tied to any object, so there’s no this; you need an object (new App().run()). main is static because the JVM calls it before any object of the class exists.

The other direction is fine: instance methods call static methods freely. A static variable has exactly one copy per class, initialized once when the class is loaded.

Mid

Where can a protected member be accessed from? Can a subclass in another package read a protected field through a parent-typed variable?

protected means package-private access plus subclasses in other packages. Through a parent-typed variable, no.

  • Inside the same package, every class can use it like default access.
  • A subclass in another package can only reach it through this or a reference typed as that subclass; through Parent other it’s a has protected access error.
  • Because it opens the whole package, protected is wider than most people think; usually keep fields private and expose only protected methods to subclasses.

Senior

What problems does static mutable state cause in a Spring application?

It’s global state shared across every request and thread, so it invites race conditions, poor testability and memory leaks.

  • State leaks between tests and can’t be mocked.
  • Ever-growing maps leak memory; in multi-classloader environments it may never be released.
  • Use container-managed singleton beans, bounded caches (Caffeine), or external stores such as Redis or a database.

Useful phrases for interviews

  • “The constructor enforces the invariants, so an invalid object can never exist.”
  • “A class is the blueprint; each object created with new is an instance with its own state on the heap.”
  • “As soon as I declare any constructor, the compiler stops generating the default one, which matters for JPA and Jackson.”
  • “I start with the narrowest access modifier, usually private, and widen it only when there’s a real need.”
  • “A static member belongs to the class, so every instance shares it and there’s no this.”
  • “Mutable static state is a global variable in disguise; in Spring I’d use a singleton bean instead.”
  • “Within the same package, protected behaves like package-private, which surprises a lot of people.”
  • “Packages are namespaces; packaging by feature lets me keep most classes package-private.”

Notes based on the Fundamentals of Backend course (Ronin Engineer) and the Hỏi Dân IT Java Core material, plus my own research, rewritten in my own words. The slides’ reference book is Y. Daniel Liang, Introduction to Java Programming and Data Structures (11th edition); many of their diagrams come from it.