Topic 4. Objects and Classes

As code grows beyond a few files, procedural style becomes fragile: data and behavior drift apart, and changes become risky. Object-oriented design addresses this by grouping state and behavior into class-level contracts.

Introduction to Object-Oriented Programming

In OOP, a system is a set of objects interacting through methods.

OOP interactions

This keeps responsibilities clearer. Example: Order computes totals, while EmailService handles notifications.

Using Existing Classes

In real projects, you combine your own classes with existing ones (String, List, Map, LocalDate, framework classes).

Class dependency

Core skill: understand class contracts.

  1. What inputs are valid.
  2. What is returned in normal scenarios.
  3. What exceptions can happen.
  4. What side effects exist.

Building Your Own Classes

A good class starts with invariants: states that must always remain valid.

Simple class diagram

public class Student {
    private final String name;
    private int score;

    public Student(String name, int score) {
        if (name == null || name.isBlank()) {
            throw new IllegalArgumentException("name is required");
        }
        if (score < 0) {
            throw new IllegalArgumentException("score must be >= 0");
        }
        this.name = name;
        this.score = score;
    }

    public void addScore(int delta) {
        if (delta > 0) {
            score += delta;
        }
    }

    public int getScore() {
        return score;
    }
}

Static Fields and Methods

static means member belongs to the class, not an instance.

Static members

public class IdGenerator {
    private static long next = 1;

    public static long nextId() {
        return next++;
    }
}

Use static for constants, factories, utility behavior. Avoid uncontrolled mutable global state.

Method Parameters

Method parameters define input contracts.

Important theory

  1. Parameter type constrains allowed inputs.
  2. Parameter names should reflect domain meaning (amount, studentId).
  3. Long parameter lists increase error probability.

How Java passes parameters

Java always passes arguments by value:

  • primitives: value is copied,
  • objects: reference value is copied.

Implication:

  • called method cannot rebind caller variable to a new object,
  • called method can mutate the object referenced by both sides.
public class ParamDemo {
    static void changeInt(int n) {
        n = 99;
    }

    static void changeScore(Student s) {
        s.addScore(10);
    }
}

Practical parameter design steps

  1. Define minimal required inputs.
  2. If parameter count grows beyond 3-4, consider request object.
  3. Validate preconditions (null, ranges, format).
  4. Be explicit about mutation behavior.

Object Construction

Constructor goal: create a valid object immediately.

Weak beginner pattern: create empty object, then “fix it later” via setters. That introduces invalid intermediate states.

Better flow:

  1. Identify mandatory fields.
  2. Pass them to constructor.
  3. Validate inputs in constructor.
  4. Throw clear exceptions for invalid data.
  5. Ensure object is usable right after construction.
public class BankAccount {
    private final String owner;
    private long balance;

    public BankAccount(String owner, long initialBalance) {
        if (owner == null || owner.isBlank()) {
            throw new IllegalArgumentException("owner is required");
        }
        if (initialBalance < 0) {
            throw new IllegalArgumentException("initialBalance must be >= 0");
        }
        this.owner = owner;
        this.balance = initialBalance;
    }
}

Packages

package organizes classes by responsibility, not random folders.

It solves:

  1. Logical project structure.
  2. Visibility boundaries (public, package-private, protected).

Beginner mental model

  • Package = district.
  • Class = building in that district.
  • import = address used to reach another building.

Example structure:

com.course.courseweb
├── controller
│   └── ArticleController
├── service
│   └── ArticleService
├── repo
│   └── ArticleRepository
└── model
    └── Article

Package declaration:

package com.course.courseweb.service;

Import usage:

import com.course.courseweb.model.Article;

Documentation Comments

Use Javadoc for public APIs and shared team contracts.

Describe:

  1. method purpose,
  2. input constraints,
  3. return behavior,
  4. thrown exceptions.

Class Design Hints

  1. One class should solve one primary responsibility.
  2. Protect invariants in constructors and critical methods.
  3. Keep public API minimal and clear.
  4. Keep fields private by default.
  5. Use meaningful names for classes, methods, and parameters.
  6. Avoid “god objects” that know and do too much.
  7. If a method needs too much explanation, simplify the method first.
Glossary
bytecode
Platform-independent compiled code that the JVM can execute.
class
A blueprint that defines fields and methods for objects in object-oriented programming.
object
A runtime instance of a class with its own state and behavior.
method
A named block of behavior that belongs to a class or object and can be called by code.
field
A variable stored inside a class or object that represents part of its state.
constructor
A special method-like block used to create and initialize a new object.
package
A namespace that groups related Java classes and helps organize code.
interface
A contract that defines methods a class can implement without prescribing all internal details.
generics
A language feature that lets code work with types as parameters while preserving type safety.
type erasure
The Java compiler process that removes most generic type details from runtime bytecode.
collection
A data structure that stores a group of elements and provides operations over them.
list
An ordered collection where elements have positions and duplicates are allowed.
set
A collection that stores unique elements and is commonly used for membership checks.
map
A key-value data structure where each key points to a value.
queue
A collection designed for processing elements in a defined order, often first-in-first-out.
lambda
A compact function-like expression used to pass behavior as data.
functional interface
An interface with one abstract method, suitable for lambdas and method references.
stream
A Java API for processing data sequences with operations such as map, filter, and reduce.
optional
A container object that represents a value that may or may not be present.
thread
An independent path of execution inside a running program.
synchronization
Coordination that protects shared data when multiple threads access it.
heap
The runtime memory area where Java objects are allocated.
stack
The runtime memory area that stores method calls, local variables, and call frames.
garbage collector
A JVM component that automatically frees memory occupied by objects no longer reachable.
memory leak
A situation where memory remains occupied because objects are still referenced but no longer useful.