Classes and Objects in Java: Build and Trace Two Objects Step by Step

Build a Java Student class, create two independent objects, and trace fields, methods, aliases, null references, output, and common errors step by step.

KnowledgeGate Team

Exam prep & CS education

Updated 10 Oct 20266 min read

Reading a Java class declaration does not automatically explain what exists after new runs. A class defines available data and operations; each new Student(...) constructs one object with its own field values. Assigning a second reference does not construct another object, and both references can then reach the same state. The Coding & DSA Courses for Placements category places this foundation in a wider learning route.

Classes and objects in Java: the precise mental model

Keep the definition and created data separate:

Term

Meaning in the Student example

Class

Student defines the type, including its fields, constructor, and methods.

Object or instance

A constructed Student, such as the object carrying "Riya" and 72.

Field

Per-object data, here name and marks.

Instance method

Behaviour called through an object, such as addGraceMarks(8).

Constructor

Code that initialises a new object when new Student(...) runs.

Reference variable

A variable such as riya that provides access to a Student object.

The class is shared, while each constructed object can hold different state. Methods belong to every Student, but a call operates on the referenced object. Classes and objects answer what state exists and which reference reaches it; encapsulation, inheritance, abstraction, and polymorphism answer later design questions about protecting, specialising, exposing, and dispatching that state. OOP for Teaching CS Exams: Classes and Inheritance places this inside the broader OOP concept set.

Trace creation by counting only new expressions:

  1. After Student a;, objects created = 0.

  2. After a = new Student("Asha", 10);, objects created = 1.

  3. After Student b = a;, objects created remains 1.

  4. After b = new Student("Bharat", 20);, total objects created = 2.

Student a; declares a reference. It creates zero Student objects.

Java class anatomy: fields, constructor, this, and methods

Our class has private fields String name and int marks. Its constructor has the class name and no return type. In this.name = name, this.name is the current object's field and bare name is the parameter.

addGraceMarks mutates that object's marks, hasPassed computes from its state, getMarks reads it, and printResult prints the values. private blocks unrelated direct changes; methods provide controlled access.

The Student class with its name and marks fields and four methods, and the two objects it builds: Riya with 72 marks and Aman with 35.

Classes and objects in Java: one fully runnable worked example

Save this complete source as Main.java:

java
class Student {
    private String name;
    private int marks;

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

    void addGraceMarks(int points) {
        marks += points;
    }

    boolean hasPassed() {
        return marks >= 40;
    }

    int getMarks() {
        return marks;
    }

    void printResult() {
        System.out.println(name + ": " + marks + ", passed=" + hasPassed());
    }
}

public class Main {
    public static void main(String[] args) {
        Student riya = new Student("Riya", 72);
        Student aman = new Student("Aman", 35);

        aman.addGraceMarks(8);

        riya.printResult();
        aman.printResult();
    }
}

Compile and run it:

Code
javac Main.java
java Main

Riya remains at 72, so 72 >= 40 is true. Aman starts at 35 and receives 8 marks: 35 + 8 = 43, and 43 >= 40 is true. The exact output is:

Code
Riya: 72, passed=true
Aman: 43, passed=true

The call through aman changes Aman from 35 to 43, but Riya stays at 72. The class has no shared marks value; each object has its own. Continue with the Complete Java Course.

Java object references: identity, aliasing, and null

Now extend the live values:

java
Student selected = aman;
selected.addGraceMarks(2);
System.out.println(aman.getMarks());

There is no new, so no object appears. Both references reach the same Aman object. Its mark changes from 43 to 43 + 2 = 45, so the printed value is 45.

By contrast, Student anotherAman = new Student("Aman", 45); creates a different object whose initial field values happen to match. Thus anotherAman == aman is false, while selected == aman is true. Here, == compares reference identity.

With Student waiting = null;, the reference reaches no object. Calling waiting.printResult() therefore throws NullPointerException.

Reference map where aman and selected point to one Aman object at 45 marks, riya points to its own object, and waiting points to nothing.

Common Java class and object errors, with direct fixes

Mistake

What goes wrong

Fix

Student aman; aman.printResult();

The local reference is not initialised.

Construct an object before using the reference.

Student aman = null; aman.printResult();

It compiles, but the call throws NullPointerException.

Ensure the reference points to an object before the call.

new Student()

Only Student(String, int) exists, so no zero-argument constructor is available.

Pass "Aman", 35, or explicitly define a valid zero-argument constructor.

Calling printResult() directly inside static main

It is an instance method, not a static method.

Call riya.printResult() or use another object's reference.

With public class Main, use the filename Main.java. The helper Student can remain non-public in that file. Diagnostic wording varies by JDK, but these causes do not.

For fast debugging, find every new, identify the reference receiving it, write the field values beside that object, and follow each method call through the reference on its left.

How exams and interviews test Java classes and objects

Assessments ask for class-versus-object definitions, object counts that distinguish declarations from new, alias output traces, and constructor or static-context errors. These foundations fit into a broader Technical Interview Prep: OS, DBMS, CN and OOP Answers plan.

A typical mini-trace looks like this:

java
Student x = new Student("Neha", 38);
Student y = x;
y.addGraceMarks(4);

For this mini-trace, the answer is: one object, x.getMarks() prints 42, and x == y is true.

Only one new runs. Both references reach it, and its state becomes 38 + 4 = 42. In an interview: define the class, identify its state, identify its behaviour, show an object with values, then say whether a second variable creates an object or another reference.

Java classes and objects exercises with checkable answers

  1. Write Book with fields title and pages. Construct new Book("Java Basics", 240) and print exactly Java Basics has 240 pages.

  2. Create Rectangle with width = 6, height = 4, and area() returning width * height. Then call setWidth(9) and calculate the area again. Why would a second rectangle retain its own width?

  3. Give a Box object value = 12, assign Box second = first, then run second.value = 19. Predict System.out.println(first.value).

Answers: Exercise 1 has one class, one object, and field values "Java Basics" and 240. Exercise 2 returns 6 * 4 = 24, then 9 * 4 = 36; a separately constructed rectangle keeps independent fields. Exercise 3 prints 19 because both references reach the same object.

Classes and objects in Java: the short version and next step

A class declares a type. new creates an object. A reference gives access to that object. Each independently constructed object has its own instance state. Two references can still point to one shared object. Riya has 72 marks, while the shared Aman object has 45.

Retype the program with Aman starting at 31 and receiving 10 grace marks. Predict 31 + 10 = 41 before running it. If you still need language fundamentals, use the Complete Java Course linked above. If you are ready to apply Java objects while learning data structures, continue with DSA Using Java: Placement Preparation Course.

Now create one class from daily life, construct two objects with different values, mutate only one, and trace the exact output by hand before compiling.