Classes and Objects in Java: Fields, Constructors and Encapsulation

admin6 min read
In this tutorial
  1. Class versus object
  2. Defining a class
  3. Creating objects with new
  4. Constructors
  5. Encapsulation: protect your data
  6. toString, equals and hashCode
  7. Records: data classes in one line
  8. static members
  9. Common mistakes
  10. Practice
  11. Summary

Java is an object-oriented language. Instead of writing one long list of instructions, you model your program as a set of objects that each hold some data and know how to do things with it. A banking app has accounts, customers and transactions; a school app has students, courses and grades.

This tutorial shows how to define your own classes, create objects from them, and protect their data properly.

Class versus object

A class is a blueprint. An object is a thing built from that blueprint.

Student is a class. Ada, Chidi and Fatima are three Student objects. They share the same structure (each has a name and a matric number) but hold different values.

Defining a class

public class Student {
    String name;
    String matricNumber;
    int level;

    void introduce() {
        System.out.println("Hi, I'm " + name + ", a " + level + " level student.");
    }
}
  • name, matricNumber and level are fields (also called instance variables). Each object gets its own copy.
  • introduce() is an instance method. It can read the fields of the object it is called on.

Creating objects with new

Student ada = new Student();
ada.name = "Ada";
ada.matricNumber = "CSC/2023/001";
ada.level = 200;
ada.introduce(); // Hi, I'm Ada, a 200 level student.

new Student() allocates a new object in memory and returns a reference to it, which we store in the variable ada. Fields you do not set get default values: 0 for numbers, false for booleans and null for objects.

Constructors

Setting every field by hand is tedious and easy to forget. A constructor runs when the object is created and makes sure it starts in a valid state:

public class Student {
    String name;
    String matricNumber;
    int level;

    Student(String name, String matricNumber, int level) {
        this.name = name;
        this.matricNumber = matricNumber;
        this.level = level;
    }
}

Student ada = new Student("Ada", "CSC/2023/001", 200);

A constructor has the same name as the class and no return type.

The this keyword

Inside the constructor, the parameter name hides the field name. this.name means “the field of this object”, so this.name = name copies the parameter into the field.

Overloaded constructors

You can provide several constructors and have one call another with this(...):

Student(String name, String matricNumber) {
    this(name, matricNumber, 100); // new students start at 100 level
}

If you write no constructor at all, Java provides an empty default one. As soon as you write any constructor, the default one disappears.

Encapsulation: protect your data

Right now anyone can write ada.level = -50;, which makes no sense. Encapsulation means hiding fields behind methods that enforce the rules.

  1. Make fields private so only the class itself can touch them.
  2. Provide public methods to read them (getters) and, where it makes sense, to change them with validation.
public class BankAccount {
    private final String accountNumber;
    private final String owner;
    private double balance;

    public BankAccount(String accountNumber, String owner) {
        this.accountNumber = accountNumber;
        this.owner = owner;
    }

    public void deposit(double amount) {
        if (amount <= 0) {
            throw new IllegalArgumentException("Deposit must be positive");
        }
        balance += amount;
    }

    public void withdraw(double amount) {
        if (amount > balance) {
            throw new IllegalStateException("Insufficient funds");
        }
        balance -= amount;
    }

    public double getBalance() {
        return balance;
    }

    public String getOwner() {
        return owner;
    }

    @Override
    public String toString() {
        return "BankAccount[" + accountNumber + ", " + owner + ", balance=" + balance + "]";
    }

    public static void main(String[] args) {
        BankAccount acc = new BankAccount("0123456789", "Ada");
        acc.deposit(10_000);
        acc.withdraw(2_500);
        System.out.println(acc);              // BankAccount[0123456789, Ada, balance=7500.0]
        System.out.println(acc.getBalance()); // 7500.0
    }
}

Notice there is no setBalance. The only way to change the balance is through deposit and withdraw, which enforce the rules. That is the real point of encapsulation: not boilerplate getters and setters for everything, but controlling how an object’s state can change.

The final fields can only be assigned once, in the constructor. An account number should never change, so final documents and enforces that.

toString, equals and hashCode

Every class inherits these methods from Object:

  • toString() decides what you see when you print the object. The default (BankAccount@1b6d3586) is useless, so override it.
  • equals() decides whether two objects are “the same”. The default compares references.
  • hashCode() must be consistent with equals(). If two objects are equal, they must have the same hash code, or they will misbehave in a HashMap or HashSet.
import java.util.Objects;

public class Point {
    private final int x;
    private final int 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 Objects.hash(x, y);
    }
}

Your IDE can generate these for you. In IntelliJ, press Alt+Insert (Cmd+N on macOS).

Records: data classes in one line

For simple classes that just carry data, Java 16+ gives you records. This single line generates a constructor, private final fields, accessor methods, equals, hashCode and toString:

public record Course(String code, String title, int units) { }

Course c = new Course("CSC201", "Object-Oriented Programming", 3);
System.out.println(c.title()); // Object-Oriented Programming
System.out.println(c);         // Course[code=CSC201, title=Object-Oriented Programming, units=3]

Records are immutable. Use them for values such as DTOs, API responses and coordinates. Use regular classes when an object has behaviour and changing state, like BankAccount.

static members

A static field belongs to the class, not to any one object, so all objects share it:

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

    public Student(String name) {
        this.name = name;
        count++;
    }

    public static int getCount() {
        return count;
    }
}

After creating three students, Student.getCount() returns 3.

Common mistakes

  • Public fields. They let any code put your object into an invalid state.
  • Forgetting this in a constructor, so name = name; assigns the parameter to itself and the field stays null.
  • Overriding equals without hashCode. Objects then get “lost” in hash-based collections.
  • Getters and setters for everything. A setter for every field is just a public field with extra steps. Only expose what callers genuinely need.

Practice

  1. Create a Product class with a name, price and quantity. Prevent negative prices and quantities.
  2. Add a restock(int amount) method and a sell(int amount) method that refuses to sell more than is in stock.
  3. Rewrite a simple Book(title, author, year) class as a record and compare how much code you saved.

Summary

  • A class is a blueprint; objects are instances created with new.
  • Constructors put objects into a valid starting state; use this to refer to fields.
  • Encapsulation means private fields plus methods that enforce your rules.
  • Override toString, and override equals and hashCode together.
  • Use records for simple immutable data carriers.

Next: learn how classes relate to each other in inheritance vs composition.

Ask a question or leave a comment

Your email address will not be published. Required fields are marked *