Skip to content
Educora
Intermediate18 min7 / 18

Classes and objects

Create your own types: fields, constructors, this, methods, encapsulation, getters and setters, and static members.

Check yourself
In this lesson you will learn
  • Write a class with fields, a constructor and methods, and create objects from it
  • Explain what the this keyword means
  • Encapsulate an object with private fields, getters and setters

A taxi app tracks thousands of cars: each has a brand, a year and a mileage, and each can drive. Creating separate variables for every car is impossible. Java's answer is classes: you describe once what a car is, and then you create as many objects from that description as you need.

Class, object and constructor

A class is a blueprint for objects: it describes what data an object will hold (its fields) and what it can do (its methods). An object is a concrete instance created with the new operator. When an object is created, a special method runs — the constructor: it has the same name as the class and no return type.

Java
public class Main {
    public static void main(String[] args) {
        Car first = new Car("Toyota", 2019);
        Car second = new Car("Kia", 2023);
        first.drive(120);
        first.drive(35);
        second.drive(60);
        System.out.println(first.brand + ": " + first.mileage + " km");
        System.out.println(second.brand + ": " + second.mileage + " km");
    }
}

class Car {
    String brand;
    int year;
    int mileage;

    Car(String brand, int year) {
        this.brand = brand;
        this.year = year;
        this.mileage = 0;
    }

    void drive(int km) {
        mileage += km;
    }
}
Expected output
Toyota: 155 km
Kia: 60 km
  • The Car class has three fields (brand, year, mileage) and one method (drive).
  • new Car("Toyota", 2019) creates a new object in memory and calls the constructor.
  • **this** is the current object itself. In this.brand = brand, the left side is the object's field and the right side is the constructor's parameter — since the names are the same, this tells them apart.
  • Each object has its own fields: first drove 155 km and second 60 km — neither affects the other.

Encapsulation: getters and setters

In the Car class anyone can write first.mileage = -500; — which makes no sense. Encapsulation means hiding an object's data and giving access to it only through methods that check it. Fields are declared private, and you write getters to read them and setters or other public methods to change them.

Java
public class Main {
    public static void main(String[] args) {
        BankAccount acc = new BankAccount("Leyla", 50);
        acc.deposit(30);
        acc.withdraw(100);
        acc.withdraw(20);
        System.out.println(acc.getOwner() + " has " + acc.getBalance() + " AZN");
        System.out.println(acc);
    }
}

class BankAccount {
    private final String owner;
    private double balance;

    BankAccount(String owner, double balance) {
        this.owner = owner;
        this.balance = balance;
    }

    public String getOwner() { return owner; }
    public double getBalance() { return balance; }

    public void deposit(double amount) {
        if (amount > 0) balance += amount;
    }

    public void withdraw(double amount) {
        if (amount > balance) {
            System.out.println("Not enough money!");
            return;
        }
        balance -= amount;
    }

    @Override
    public String toString() {
        return "BankAccount[" + owner + ", " + balance + "]";
    }
}
Expected output
Not enough money!
Leyla has 60.0 AZN
BankAccount[Leyla, 60.0]

Now only the deposit and withdraw methods can change the balance, and they follow the rules: negative amounts are refused, and you cannot take out more than the account holds. The owner field is final: it is set once in the constructor and never changes, so it has no setter. The toString() method decides how the object looks when printed with println.

ModifierWho can see it?
publiceveryone
protectedthe same package and subclasses
(no modifier)only the same package
privateonly the class itself
Access modifiers — from most open to most closed

Several constructors and static members

Constructors can be overloaded just like methods. One constructor can call another with this(...), which avoids repeating code. A static field belongs not to individual objects but to the whole class: there is one copy of it, shared by all objects.

Java
public class Main {
    public static void main(String[] args) {
        Student a = new Student("Aysel");
        Student b = new Student("Murad", 9);
        System.out.println(a.info());
        System.out.println(b.info());
        System.out.println("Students created: " + Student.count);
        Student c = b;
        c.setGrade(10);
        System.out.println(b.info());
    }
}

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

    Student(String name, int grade) {
        this.name = name;
        setGrade(grade);
        count++;
    }

    Student(String name) {
        this(name, 5);
    }

    public void setGrade(int grade) {
        if (grade >= 1 && grade <= 11) {
            this.grade = grade;
        }
    }

    public String info() {
        return name + ", grade " + grade;
    }
}
Expected output
Aysel, grade 5
Murad, grade 9
Students created: 2
Murad, grade 10
1 / 5

Key points

  • A class is a blueprint; an object is a concrete instance created with new.
  • A constructor has the class's name, no return type, and sets the fields' starting values.
  • this is the current object; this(...) calls another constructor of the same class.
  • Encapsulation: fields are private, and access goes through getters, setters and methods that check the data.
  • A static field is shared by all objects; object variables hold references.

Check yourself

10 questions. Every correct answer earns XP.

1 / 10
How does a constructor differ from an ordinary method?