Course topics

By WebNest Studio Engineering Team

Java - Core Tutorial

Classes and Objects

A class is a user-defined blueprint that describes the state (fields) and behavior (methods) that a category of objects will share. It does not itself occupy memory for instance data — it is a template. An object is a concrete instance of a class, created at runtime with the new keyword, and it occupies actual memory on the heap holding real values for the class's fields.

A common real-world analogy: a class is like an architect's blueprint for a house, describing rooms, doors, and dimensions, while an object is an actual house built from that blueprint. You can build many houses (objects) from one blueprint (class), and each house has its own furniture and occupants (its own field values) even though they all share the same structural design.

Why it matters

Everything you build in Java is made of classes and the objects created from them. The idea that trips up newcomers is that a variable does not contain an object; it holds a reference to one. Once that is clear, behaviour such as "I changed b and a changed too" stops being a mystery.

Watch: Classes and Objects in Java, in Detail

Prefer to watch? This video explains classes and objects in detail: declaring a class, creating objects with new, and how each object keeps its own state.

Watch on YouTube

Declaring a Class

A class declaration consists of an optional access modifier, the class keyword, a name following PascalCase convention, and a body enclosed in braces containing fields, constructors, and methods. Fields declared inside a class but outside any method are called instance variables, and each object created from the class gets its own independent copy of them.

Creating Objects

An object is created using the new keyword followed by a constructor call: ClassName obj = new ClassName();. This statement does three things in order: it allocates memory on the heap for the object, calls the constructor to initialize its fields, and assigns the resulting memory reference to the variable obj. The variable itself does not hold the object — it holds a reference to where the object lives in memory.

Accessing Members

Once you have an object reference, you access its fields and methods using the dot (.) operator: obj.fieldName or obj.methodName(). Each object maintains its own copy of instance variables, so changing a field on one object never affects another object created from the same class.

  • A class is compiled once; objects are created as many times as needed at runtime.
  • Each object has its own instance variables but shares the same method code defined in the class.
  • An uninitialized object reference holds null until assigned with new.

State, Behavior and Identity

Every object has three characteristics. Its state is the current value of its fields, such as a car's model and speed. Its behavior is what its methods can do, such as accelerate(). Its identity is the fact that it is a distinct object in memory: two cars can have exactly the same model and speed and still be two different objects.

References: Two Variables, One Object

Because a variable holds a reference rather than the object itself, assigning one object variable to another copies the reference, not the object. After Car b = a; there is still only one Car on the heap, and a and b both point to it, so a change made through b is visible through a. To get a second, independent object you must call new again.

The == operator on object variables compares these references. It is true only when both variables point to the same object, even if two separate objects hold identical field values. The second example below shows both cases.

Examples

One class, two independent objects with their own state

Java
public class Student {
    String name;
    int marks;

    void showDetails() {
        System.out.println(name + " scored " + marks);
    }

    public static void main(String[] args) {
        Student s1 = new Student();
        s1.name = "Riya";
        s1.marks = 88;

        Student s2 = new Student();
        s2.name = "Kabir";
        s2.marks = 92;

        s1.showDetails();
        s2.showDetails();
    }
}
Output
Riya scored 88
Kabir scored 92

Copying a reference does not copy the object; == compares references

Java
public class Car {
    String model;
    int speed;

    void accelerate(int amount) {
        speed += amount;
    }

    public static void main(String[] args) {
        Car a = new Car();
        a.model = "Swift";

        Car b = a; // no new object: b refers to the same Car as a
        b.accelerate(40);
        System.out.println(a.model + " speed read through a: " + a.speed);

        Car c = new Car(); // a separate object with the same field values
        c.model = "Swift";
        c.speed = 40;
        System.out.println("a == b: " + (a == b));
        System.out.println("a == c: " + (a == c));
    }
}
Output
Swift speed read through a: 40
a == b: true
a == c: false

Common Mistakes

  • Believing a class occupies memory the way an object does — a class is only a template until an object is instantiated from it.
  • Forgetting to use "new" and trying to use a class name directly as if it were an object.
  • Assuming two object references pointing to the same object are independent copies — reassigning a field through one reference affects the other, since both point to the same memory.

Exercise

Create a Book class with a title and a page count, and a method isLong() that returns true when the book has more than 300 pages. Create two books and print the result for each.

Expected output: Clean Code: true then Java Basics: false

Java · starter code
class Book {
    String title;
    int pages;

    // TODO: isLong() returns true when pages is greater than 300
}

public class BookDemo {
    public static void main(String[] args) {
        // TODO: create a Book titled "Clean Code" with 464 pages
        // TODO: create a Book titled "Java Basics" with 180 pages
        // TODO: print "<title>: <isLong()>" for each
    }
}
Show hints
  • Create each object with new Book() and set its fields with the dot operator.
  • Each object has its own title and pages; setting one does not affect the other.
Show solution
Java · solution
class Book {
    String title;
    int pages;

    boolean isLong() {
        return pages > 300;
    }
}

public class BookDemo {
    public static void main(String[] args) {
        Book first = new Book();
        first.title = "Clean Code";
        first.pages = 464;

        Book second = new Book();
        second.title = "Java Basics";
        second.pages = 180;

        System.out.println(first.title + ": " + first.isLong());
        System.out.println(second.title + ": " + second.isLong());
    }
}

Quick quiz

1. What does the new keyword do?

  • A. Declares a new class
  • B. Creates an object on the heap, runs a constructor, and returns a reference to it
  • C. Copies an existing object
  • D. Reserves a variable name
Show answer

B. new allocates memory for the object, initialises it through a constructor, and gives back a reference that you store in a variable.

2. You create two objects of the same class and set a field on the first. What happens to that field on the second?

  • A. It changes too
  • B. It becomes null
  • C. It is unchanged; each object has its own copy of instance fields
  • D. The code does not compile
Show answer

C. Instance fields belong to each object separately. Only static fields are shared.

3. After Student a = new Student(); Student b = a; b.name = "Ravi";, what is a.name?

  • A. null
  • B. It does not compile
  • C. An empty string
  • D. Ravi
Show answer

D. b = a copies the reference, so both variables point to the same object. A change made through b is visible through a.

Interview questions

What is the difference between a class and an object?

Show answer

A class is a definition written in source code: it lists the fields and methods its objects will have. It exists once. An object is a concrete instance created from that class at runtime with new; it occupies memory and holds its own values for the fields. You can create any number of objects from one class.

Where are objects and their reference variables stored?

Show answer

Objects are always created on the heap. A local variable that refers to an object lives on the stack frame of its method and holds only the reference. When the method returns, the variable disappears; the object remains on the heap until nothing refers to it, at which point the garbage collector can reclaim it.

Key Points to Remember

  • A class is a blueprint; an object is a runtime instance of that blueprint, created with "new".
  • Each object has its own copy of instance variables, but all objects share the same method definitions.
  • Object variables hold references to heap memory, not the object data itself.
  • Every object has state (field values), behavior (methods) and identity (being a distinct object), and == on objects compares identity.

Practice in the playground

Write and run your own code for this topic, or start from the exercise or an example. Runs plain Java 17. Frameworks such as Spring, and databases, are not available here. Your code for each topic is kept in this browser.

Run the examples

Change an input, predict the result, then compare it with the output. Explain why the result changes.

WebNest Studio

Written by

WebNest Studio Engineering Team

Practical lessons from developers working with Java, Python, React, databases and production systems.

Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering