Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

JV
Java
0/14 completed
Beginner
Hello JavaVariables and typesControl flowMethodsArrays and strings
Intermediate
Classes and objectsInheritance and interfacesCollectionsExceptions
Advanced
GenericsLambdas and streamsRecords, enums and pattern matching
Pro
Concurrency and virtual threadsBuild tools, testing and real projects
Tracks / Java / Intermediate

Classes and objects

Java is an object-oriented language: programs are built from objects that bundle data (fields) with behaviour (methods). A class is the blueprint, and each object made from it is an instance.

Your first class

java
class Dog {
    String name;          // fields: each Dog has its own
    String breed;
    int tricks = 0;

    Dog(String name, String breed) {      // constructor: runs when you write new Dog(...)
        this.name = name;                 // this.name = the field; name = the parameter
        this.breed = breed;
    }

    void learnTrick() {                   // an instance method
        tricks++;
    }

    String describe() {
        return name + " the " + breed + " knows " + tricks + " tricks";
    }
}

public class Main {
    public static void main(String[] args) {
        Dog rex = new Dog("Rex", "beagle");
        Dog bella = new Dog("Bella", "husky");

        rex.learnTrick();
        rex.learnTrick();

        System.out.println(rex.describe());
        System.out.println(bella.describe());
    }
}
Output
Rex the beagle knows 2 tricks
Bella the husky knows 0 tricks
  • new Dog(...) creates an object and runs the constructor.
  • this refers to the current object.
  • Every object has its own copy of the fields: Rex's tricks aren't Bella's.

A file can contain several classes, but only one public class, which must match the file name. In real projects, each class usually gets its own file.

Encapsulation: private fields

If anyone can change any field, objects can end up in invalid states (like a negative balance). Encapsulation hides fields with private and exposes safe methods instead:

java
class BankAccount {
    private final String owner;     // final: set once in the constructor, never changed
    private double balance;

    BankAccount(String owner, double openingBalance) {
        if (openingBalance < 0) throw new IllegalArgumentException("Opening balance can't be negative");
        this.owner = owner;
        this.balance = openingBalance;
    }

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

    public boolean withdraw(double amount) {
        if (amount > balance) return false;    // refuse instead of going negative
        balance -= amount;
        return true;
    }

    public double getBalance() { return balance; }     // a "getter"
    public String getOwner() { return owner; }
}

public class Main {
    public static void main(String[] args) {
        BankAccount acct = new BankAccount("Asha", 100);
        acct.deposit(50);
        System.out.println(acct.withdraw(30));
        System.out.println(acct.withdraw(500));
        System.out.println(acct.getOwner() + " has " + acct.getBalance());
    }
}
Output
true
false
Asha has 120.0

Trying acct.balance = 1_000_000; from Main won't compile: balance has private access in BankAccount. The class controls every change to its data.

Access modifiers

Modifier Visible from
private Only inside the same class
(none) The same package
protected The same package and subclasses
public Everywhere

Rule of thumb: fields private, methods public only if other classes need them.

static: belonging to the class

static fields and methods belong to the class itself, not to any one object. That's why main is static: Java calls it before any object exists.

java
class User {
    private static int count = 0;      // shared by all users
    private final int id;
    private final String name;

    User(String name) {
        count++;
        this.id = count;
        this.name = name;
    }

    static int getCount() { return count; }

    @Override
    public String toString() {           // used when printing the object
        return "User#" + id + "(" + name + ")";
    }
}

public class Main {
    public static void main(String[] args) {
        User a = new User("Asha");
        User b = new User("Rahul");
        System.out.println(a + " " + b);
        System.out.println("Users created: " + User.getCount());
        System.out.println(Math.max(3, 9));     // Math's methods are static too
    }
}
Output
User#1(Asha) User#2(Rahul)
Users created: 2
9

toString, equals and hashCode

Every class inherits these from Object. The defaults are rarely what you want:

java
class Point {
    final int x, y;
    Point(int x, int y) { this.x = x; this.y = y; }
}

class BetterPoint {
    final int x, y;
    BetterPoint(int x, int y) { this.x = x; this.y = y; }

    @Override
    public String toString() { return "(" + x + ", " + y + ")"; }

    @Override
    public boolean equals(Object o) {
        return o instanceof BetterPoint p && p.x == x && p.y == y;
    }

    @Override
    public int hashCode() { return java.util.Objects.hash(x, y); }
}

public class Main {
    public static void main(String[] args) {
        System.out.println(new Point(1, 2).equals(new Point(1, 2)));
        System.out.println(new BetterPoint(1, 2).equals(new BetterPoint(1, 2)));
        System.out.println(new BetterPoint(1, 2));
    }
}
Output
false
true
(1, 2)

The default equals checks whether two references point to the same object. If you override equals, always override hashCode too, or objects will misbehave in HashMap and HashSet. (In the modern Java lesson you'll see records, which generate all of this for you.)

Constructors: overloading and chaining

java
class Pizza {
    private final String size;
    private final String[] toppings;

    Pizza(String size, String... toppings) {
        this.size = size;
        this.toppings = toppings;
    }

    Pizza() {
        this("medium", "cheese");       // call the other constructor
    }

    @Override
    public String toString() {
        return size + " pizza with " + String.join(", ", toppings);
    }
}

public class Main {
    public static void main(String[] args) {
        System.out.println(new Pizza());
        System.out.println(new Pizza("large", "mushroom", "olives", "basil"));
    }
}
Output
medium pizza with cheese
large pizza with mushroom, olives, basil

References and null

Variables of class types hold references (like addresses) to objects. Two variables can refer to the same object, and a reference can be null (pointing at nothing):

java
class Counter {
    int value;
}

public class Main {
    public static void main(String[] args) {
        Counter a = new Counter();
        Counter b = a;                  // same object, two names
        b.value = 10;
        System.out.println(a.value);

        Counter c = null;
        System.out.println(c.value);
    }
}
Output
10
Exception in thread "main" java.lang.NullPointerException: Cannot read field "value" because "<local3>" is null
	at Main.main(Main.java:13)

NullPointerException is the most common Java crash. Check for null, avoid returning it where you can (return an empty list or Optional instead), and initialise fields in constructors.

Practice

  1. Write a Rectangle class with private width and height, a constructor that rejects non-positive values, and area(), perimeter() and toString() methods.
  2. Write a Product class with a name and price, and a Cart class that holds an array of up to 10 products, with add(Product) and total() methods.
  3. Give Product an equals and hashCode based on its name.
✎ Check your understanding

1.What does a constructor do?

2.Why make fields private?

3.What does a static field belong to?

← Arrays and strings