Skip to lesson

Objects: instances of a class

An object is an instance of a class: a real thing built from the class at runtime with new, holding its own field values. You reach it through a reference variable, like s in Student s = new Student();.

What is an object?

An object is an instance of a class: one real thing with its own state (the data it holds), behaviour (the actions it can do) and identity (what makes it different from every other object). It is created from the class while the program runs.

In Classes: the blueprint of objects (opens in a new tab), Student was only a plan. An object is one real student made from that plan while the program runs: Aarav with 87 marks is one object, Priya with 91 marks is another. Each one is an instance of the Student class.

Every object has three things. Its state is the values in its fields right now. Its behaviour is the methods it can run. Its identity means it is its own separate thing in memory, even when another object holds exactly the same values.

The class is written once in your code; objects are created at runtime, as many as the program needs. A blueprint is not a house, and a class is not an object.

Reading Student s = new Student();

new creates an object of a class at runtime, gives each of its fields a default value and returns a reference to it. Creating an object this way is called instantiation.

One line, Student s = new Student();, creates a student you can work with. Read it from the right: new builds the object and hands back a reference, a value that says where the object is, and = stores it in s.

Syntax
ClassName variableName = new ClassName();

Example 1 · Create an object, then set and read fields

NewDemo.javaJava
class Student {    String name;    int marks;}
public class NewDemo {    public static void main(String[] args) {        Student s;        s = new Student();      // the object exists from here on        s.name = "Aarav";        s.marks = 87;        s.marks = s.marks + 5;        System.out.println(s.name + " has " + s.marks + " marks");    }}
Output
Aarav has 92 marks

What this code does

  • Student s; only makes the variable. The object exists after new Student() runs and its reference is stored in s.
  • s.name = "Aarav"; writes into the object's field. s.marks = s.marks + 5; reads 87, adds 5 and writes 92 back.

Student s; only declares the variable. new Student() is the instantiation, the step that makes the object, and the brackets after the class name are needed.

You can split the line in two: Student s; then s = new Student();. Until the second line runs, there is no object.

Reference variables: stack and heap

A reference variable is a variable of a class type, like s in Student s. It does not hold the object itself, only a reference that says where the object is on the heap.

s is not the student. Java keeps each running method's local variables, like s, on the stack, and every object made with new on the heap; s holds only an arrow to its object.

Student s = new Student(); in main. The variable s is on the stack and holds only a reference, drawn as an arrow. The arrow leads to the Student object on the heap, which holds the fields name = "Aarav" and marks = 87.

Example 2 · Printing the reference variable itself

PrintRefDemo.javaJava
class Student {    String name;    int marks;}
public class PrintRefDemo {    public static void main(String[] args) {        Student s = new Student();        s.name = "Diya";        s.marks = 93;        System.out.println(s);        System.out.println(s.name + " " + s.marks);    }}
Sample output (the part after @ differs on your computer)
Student@76ed5528
Diya 93

What this code does

  • println(s) does not print the fields. It prints the class name, @ and a number in hexadecimal (base 16) that Java made for this object, its hash code.
  • To see the data, follow the arrow with the dot: s.name, s.marks. toString() (opens in a new tab) shows how to change this text.

This is the same idea you met with arrays in Arrays and methods (opens in a new tab): an array variable also holds a reference, not the boxes themselves.

Using an object: the dot operator

The dot operator (.) reaches inside the object that a reference points to: t.fare reads or writes a field of that object, and t.printTicket() calls an instance method on it.

Priya's train ticket must print itself. The dot operator (.) follows the reference to its object: t.fare = 450; writes a field, t.fare reads it, and t.printTicket() runs the method for that object.

Example 3 · Call an instance method on an object

TicketDemo.javaJava
class TrainTicket {    String passenger;    String from;    String to;    int fare;
    void printTicket() {        System.out.println("Passenger: " + passenger);        System.out.println(from + " -> " + to + ", Rs. " + fare);    }}
public class TicketDemo {    public static void main(String[] args) {        TrainTicket t = new TrainTicket();        t.passenger = "Priya";        t.from = "Chennai";        t.to = "Bengaluru";        t.fare = 450;        t.printTicket();    }}
Output
Passenger: Priya
Chennai -> Bengaluru, Rs. 450

What this code does

  • The four lines with t. fill the fields of the object that t refers to.
  • t.printTicket() runs the method for that object, so passenger inside the method means this ticket's passenger, Priya.

Example 4 · Two objects, two sets of fields

TwoObjectsDemo.javaJava
class Account {    String holder;    int balance;}
public class TwoObjectsDemo {    public static void main(String[] args) {        Account a1 = new Account();        Account a2 = new Account();        a1.holder = "Priya";        a1.balance = 2000;        a2.holder = "Arjun";        a2.balance = 500;
        a1.balance = a1.balance - 300;        System.out.println(a1.holder + ": Rs. " + a1.balance);        System.out.println(a2.holder + ": Rs. " + a2.balance);    }}
Output
Priya: Rs. 1700
Arjun: Rs. 500

What this code does

  • Two news made two objects on the heap: a1 leads to Priya's, a2 to Arjun's.
  • Taking Rs. 300 from a1.balance changes only Priya's object; Arjun still has Rs. 500.

The class is shared, the data is not: every new makes a separate object with its own copy of every field. Two variables can also lead to the same object; that case is in Many objects, references and null (opens in a new tab). Methods that change fields come in State and behaviour (opens in a new tab).

Here every object gets its values one field at a time, after new. Constructors (opens in a new tab), in the next module, fill the fields as the object is built.

Default values: fields get them, local variables do not

A default value is the value Java gives a field when new creates the object: 0 for whole numbers, 0.0 for decimals, false for boolean, '\u0000' for char and null for objects. Local variables get no default.

You create a settings object and print its fields before setting any. Java gives every field a default value when new builds the object; a local variable inside a method gets none, and reading it too early is a compile error.

Example 5 · Default values of fields

DefaultsDemo.javaJava
class Settings {    int fontSize;    double volume;    boolean darkMode;    String language;}
public class DefaultsDemo {    public static void main(String[] args) {        Settings st = new Settings();        System.out.println("fontSize = " + st.fontSize);        System.out.println("volume = " + st.volume);        System.out.println("darkMode = " + st.darkMode);        System.out.println("language = " + st.language);    }}
Output
fontSize = 0
volume = 0.0
darkMode = false
language = null

What this code does

  • No field was set, yet the program compiles and prints: new gave each field its default.
  • language = null means the field refers to no String object yet. Using it with a dot, like st.language.length(), would crash.

Example 6 · Mistake: using a variable before it has a value

NoNewDemo.javaJava
class Student {    String name;}
public class NoNewDemo {    public static void main(String[] args) {        int total;        Student s;        System.out.println(total);        s.name = "Kavya";    }}
Sample compiler output
NoNewDemo.java:9: error: variable total might not have been initialized
        System.out.println(total);
                           ^
NoNewDemo.java:10: error: variable s might not have been initialized
        s.name = "Kavya";
        ^
2 errors

What this code does

  • total and s are local variables of main, so they get no default. Reading either one is a compile error.
  • Fix: int total = 0; and Student s = new Student();. Fields got defaults in Example 5; local variables never do.

These are the same defaults a new array gets, as in Creating arrays (opens in a new tab). Java is strict with local variables on purpose: reading one too early is almost always a bug, so javac stops it before the program runs.

Next step

Check your understanding

12 quick questions