00:00

Classes and Objects in Java – Explained with Examples

Classes and objects are the foundation of Java. A class is a blueprint that describes what data something has and what it can do. An object is a real thing built from that blueprint, with its own values. Every Java program you write is made of classes, and almost everything it works with at runtime is an object.

This tutorial explains how to write a class, create objects, use references, and choose between instance and static members, with runnable examples.

1. What Are Classes and Objects?

Think of a house plan and the houses built from it. The plan (class) says every house has rooms, a door and a colour. Each house (object) is real, has its own address and colour, and can be changed without affecting the others.

ClassObject
A blueprint or templateAn instance built from the blueprint
Declared once with the class keywordCreated many times with new
Exists in the source code and as loaded metadataExists in heap memory while the program runs
Example: CarExamples: a red Tata, a white Honda

Every object has:

  • State: the values of its fields (colour, speed).
  • Behaviour: what its methods do (accelerate, brake).
  • Identity: it is a distinct object, even if another object has the same values.

2. Anatomy of a Class

Class structure
[access modifier] class ClassName [extends Parent] [implements Interfaces] {
    // fields (variables): the data
    // constructors: how objects are initialised
    // methods: the behaviour
    // nested classes, initializer blocks (optional)
}

By convention, class names use PascalCase (BankAccount), and a public class must be saved in a file with the same name (BankAccount.java).

3. Creating a Class and Objects

Here a Car class defines fields, a constructor and methods. Two objects are created from it, and each keeps its own speed:

Car.java
public class Car {
    // Fields (state)
    String brand;
    String color;
    int speed;

    // Constructor: runs when an object is created
    Car(String brand, String color) {
        this.brand = brand;
        this.color = color;
        this.speed = 0;
    }

    // Methods (behaviour)
    void accelerate(int amount) { speed += amount; }
    void brake() { speed = 0; }
    String describe() { return color + " " + brand + " at " + speed + " km/h"; }

    public static void main(String[] args) {
        Car car1 = new Car("Tata", "red");      // object 1
        Car car2 = new Car("Honda", "white");   // object 2

        car1.accelerate(60);
        car2.accelerate(40);
        car2.accelerate(30);

        System.out.println(car1.describe());
        System.out.println(car2.describe());

        car1.brake();
        System.out.println(car1.describe());
    }
}
Output
red Tata at 60 km/h
white Honda at 70 km/h
red Tata at 0 km/h
Creating objects from a class in Java

4. What Happens When You Write new?

The statement Car car1 = new Car("Tata", "red"); does several things:

  1. Declaration: Car car1 creates a reference variable that can point to a Car.
  2. Allocation: new reserves memory for a new object on the heap and sets all fields to default values (null, 0, false).
  3. Initialisation: the constructor runs and sets the fields.
  4. Assignment: the reference to the new object is stored in car1.

The variable does not contain the object itself; it holds a reference (like an address) to the object.

5. Reference Variables

Because variables hold references, copying a variable copies the reference, not the object. Two variables can then point to the same object:

References.java
public class References {
    static class Box { int value; Box(int v) { value = v; } }

    public static void main(String[] args) {
        Box a = new Box(10);
        Box b = a;                 // b refers to the SAME object as a
        b.value = 99;
        System.out.println("a.value = " + a.value);

        Box c = new Box(99);       // a different object with the same data
        System.out.println("a == b: " + (a == b));
        System.out.println("a == c: " + (a == c));

        Box d = null;              // refers to no object
        try {
            System.out.println(d.value);
        } catch (NullPointerException e) {
            System.out.println("d is null: NullPointerException");
        }
    }
}
Output
a.value = 99
a == b: true
a == c: false
d is null: NullPointerException
  • == on objects checks whether two references point to the same object.
  • To compare contents, a class overrides equals() (records do this automatically).
  • A reference set to null points to nothing; using it throws NullPointerException.

6. Fields, Methods and Constructors

MemberPurposeExample
Field (instance variable)Stores an object's stateString color;
MethodDefines behaviourvoid brake() { speed = 0; }
ConstructorInitialises a new object; same name as the class, no return typeCar(String brand, String color) { ... }
Static field/methodBelongs to the class, shared by all objectsstatic int created;

The keyword this refers to the current object. It is used to tell a field (this.brand) apart from a parameter with the same name (brand). See Constructors in Java and Methods in Java for details.

7. Instance Members vs Static Members

Instance fields exist once per object; static fields exist once per class. Here a static counter tracks how many objects were created, while each object keeps its own id:

StaticVsInstance.java
public class StaticVsInstance {
    static int created = 0;        // one copy shared by the whole class
    final int id;                  // one copy per object

    StaticVsInstance() {
        created++;
        id = created;
    }

    public static void main(String[] args) {
        StaticVsInstance x = new StaticVsInstance();
        StaticVsInstance y = new StaticVsInstance();
        StaticVsInstance z = new StaticVsInstance();
        System.out.println("x.id=" + x.id + ", y.id=" + y.id + ", z.id=" + z.id);
        System.out.println("Objects created: " + StaticVsInstance.created);
    }
}
Output
x.id=1, y.id=2, z.id=3
Objects created: 3

Static methods can be called without creating an object (Math.max(3, 5)), but they cannot use instance fields directly, because there is no "current object". Learn more in static keyword in Java.

8. Ways to Create Objects

The new keyword is by far the most common, but there are other ways:

CreateObjects.java
import java.util.List;

public class CreateObjects {
    static class Point implements Cloneable {
        final int x, y;
        Point(int x, int y) { this.x = x; this.y = y; }
        static Point origin() { return new Point(0, 0); }          // factory method
        @Override public Point clone() {
            try { return (Point) super.clone(); } catch (CloneNotSupportedException e) { throw new AssertionError(e); }
        }
        @Override public String toString() { return "(" + x + ", " + y + ")"; }
    }

    public static void main(String[] args) throws Exception {
        Point p1 = new Point(3, 4);                                   // 1. new keyword
        Point p2 = Point.origin();                                    // 2. factory method
        Point p3 = p1.clone();                                        // 3. clone()
        Point p4 = Point.class.getDeclaredConstructor(int.class, int.class)
                              .newInstance(7, 8);                     // 4. reflection
        System.out.println(List.of(p1, p2, p3, p4));
        System.out.println("p3 is a copy, not the same object: " + (p1 != p3));
    }
}
Output
[(3, 4), (0, 0), (3, 4), (7, 8)]
p3 is a copy, not the same object: true
WayWhen it is used
newEveryday object creation.
Static factory methodNamed creation, caching or returning subtypes, e.g. List.of(), LocalDate.now().
clone()Copying an existing object (copy constructors are usually preferred).
ReflectionFrameworks that create objects of classes known only at runtime.
DeserializationRebuilding objects from bytes, JSON or XML.

9. Records: Classes for Plain Data

Many classes simply hold data. Since Java 16, a record declares such a class in one line, generating the constructor, accessor methods, equals(), hashCode() and toString():

RecordDemo.java
public class RecordDemo {
    // A record: constructor, accessors, equals, hashCode and toString are generated
    record Book(String title, String author, int pages) { }

    public static void main(String[] args) {
        Book b1 = new Book("Clean Code", "Robert C. Martin", 464);
        Book b2 = new Book("Clean Code", "Robert C. Martin", 464);

        System.out.println(b1);
        System.out.println("title(): " + b1.title());
        System.out.println("b1.equals(b2): " + b1.equals(b2));
    }
}
Output
Book[title=Clean Code, author=Robert C. Martin, pages=464]
title(): Clean Code
b1.equals(b2): true

Records are immutable: their fields are final and cannot be changed after creation.

10. Anonymous Objects

If you need an object only once, you can create it without storing the reference, for example new Car("Kia", "blue").describe();. The object becomes eligible for garbage collection right after the statement finishes.

11. Object Lifetime and Garbage Collection

An object lives on the heap as long as some reference can reach it. When no references remain, for example after car1 = null; or when a local variable goes out of scope, the garbage collector may reclaim its memory. You never delete objects manually in Java. See Garbage Collection in Java.

12. Best Practices

  • Give each class one clear responsibility.
  • Make fields private and expose behaviour through methods (encapsulation).
  • Use constructors to put objects into a valid state immediately.
  • Prefer immutable objects (final fields, records) when possible.
  • Override equals(), hashCode() and toString() for value-like classes.
  • Use meaningful names: nouns for classes, verbs for methods.

13. Summary

  • A class is a blueprint with fields, constructors and methods; an object is an instance created with new.
  • Variables hold references to objects; == compares references, equals() compares content.
  • Instance members belong to each object; static members belong to the class.
  • Objects can also be created by factory methods, cloning, reflection and deserialization.
  • Records offer a compact way to write immutable data classes.

Related Tutorials

Reference: dev.java: Classes and Objects