Skip to content
Qyubie Learn
Java tutorialLesson 10 of 18 · tap to see all lessons

Java tutorial · Beginner

Java Classes and Objects: Fields, Methods, and Object References

Declare a Java class, create objects with new, use fields and instance methods, understand object references and null, and make many objects from one class.

  • Qyubie Learn Editorial Team
  • Published
  • 8 min read

Includes 2 quick checks you can do right here.

In the last lesson you saw why objects help. Now you'll build them. A class describes what every object of that kind has (its fields) and does (its methods). The new keyword then creates objects from it, as many as you need.

By the end of this lesson you will be able to:

  • declare a class with fields and methods,
  • create objects with new and use them with the dot operator,
  • explain instance variables and their default values, and
  • explain what an object reference is, including null and two variables pointing to the same object.

Declaring a class

A class has a name (PascalCase), fields for its data, and methods for its behavior:

class BankAccount {
    // fields (attributes)
    String owner;
    double balance;

    // methods (behaviors)
    void deposit(double amount) {
        balance += amount;
    }

    void showBalance() {
        System.out.printf("%s: %.2f%n", owner, balance);
    }
}

Two things are different from the methods in lesson 8:

  • These methods are not static. They belong to each object, so they work on that object's own balance.
  • Inside a method, balance and owner mean this object's fields.

UML class diagrams, which you'll draw in lab, show the same class as a box with three parts:

+---------------------------+
| BankAccount               |
+---------------------------+
| owner : String            |
| balance : double          |
+---------------------------+
| deposit(amount : double)  |
| showBalance()             |
+---------------------------+

Creating objects with new

new BankAccount() creates an object (an instance) and gives back a reference to it, which you store in a variable of the class type. Use the dot operator to reach its fields and methods.

class BankAccount {
    String owner;
    double balance;

    void deposit(double amount) {
        balance += amount;
    }

    void showBalance() {
        System.out.printf("%s: %.2f%n", owner, balance);
    }
}

public class Bank {
    public static void main(String[] args) {
        BankAccount acc = new BankAccount();   // create an object
        acc.owner = "Ana";                      // set a field
        acc.deposit(500);                       // call a method
        acc.deposit(250.50);
        acc.showBalance();
    }
}

Output:

Ana: 750.50

Several classes can share one file, as here, but only one may be public, and the file is named after it (Bank.java). In bigger projects, put each class in its own file.

Instance variables and default values

Fields declared in a class (not inside a method) are instance variables: every object gets its own copy. Unlike local variables, fields get default values if you don't set them:

Field typeDefault
int, long, double, …0 or 0.0
booleanfalse
char'\u0000' (the null character)
any object type (String, arrays, …)null
class Item {
    String name;
    int quantity;
    boolean available;
}

public class Defaults {
    public static void main(String[] args) {
        Item it = new Item();
        System.out.println(it.name);
        System.out.println(it.quantity);
        System.out.println(it.available);
    }
}

Output:

null
0
false

Many objects from one class

Each object has its own field values. Changing one doesn't touch the others:

class Student {
    String name;
    int score;

    String remark() {
        return score >= 75 ? "Passed" : "Failed";
    }
}

public class Roster {
    public static void main(String[] args) {
        Student s1 = new Student();
        s1.name = "Ana";
        s1.score = 88;

        Student s2 = new Student();
        s2.name = "Ben";
        s2.score = 70;

        Student[] all = {s1, s2};          // an array of objects
        for (Student s : all) {
            System.out.println(s.name + " - " + s.remark());
        }
    }
}

Output:

Ana - Passed
Ben - Failed

An array of objects is how you'll keep a list of records until you meet ArrayList in lesson 18.

Quick check

What does this print?
class Counter {
    int value;
    void add() { value++; }
}
public class Main {
    public static void main(String[] args) {
        Counter a = new Counter();
        Counter b = new Counter();
        a.add();
        a.add();
        b.add();
        System.out.println(a.value + " " + b.value);
    }
}

Object references

A variable of a class type doesn't hold the object itself. It holds a reference, which is like an address that leads to the object. This matters when you copy the variable:

class Box {
    int size;
}

public class Refs {
    public static void main(String[] args) {
        Box a = new Box();
        a.size = 5;
        Box b = a;        // copies the reference, not the object
        b.size = 99;
        System.out.println(a.size);
        System.out.println(a == b);

        Box c = new Box();
        c.size = 99;
        System.out.println(a == c);
    }
}

Output:

99
true
false
  • Box b = a; doesn't create a second box. Now a and b both refer to the same object, so changing it through b is visible through a.
  • == on objects asks "same object?", not "same contents?". a and c hold equal values but are different objects, so a == c is false. (That's why Strings need .equals().)

null means a reference that points to no object. Calling a method or reading a field through null causes a NullPointerException:

Student s = null;
System.out.println(s.name);   // NullPointerException

Quick check

What does this print?
class Point {
    int x;
}
public class Main {
    public static void main(String[] args) {
        Point p = new Point();
        p.x = 1;
        Point q = p;
        q.x = q.x + 10;
        p = new Point();
        p.x = 3;
        System.out.println(q.x);
    }
}

Common mistakes

  • Forgetting new: Student s; s.name = "Ana"; won't compile, because s was never given an object.
  • Calling an instance method from static main without an object: deposit(100); alone fails. Call it on an object: acc.deposit(100);.
  • Expecting b = a to copy the object. It copies the reference.
  • Comparing objects with == when you mean "same contents".
  • Making two classes public in one file.

Summary

  • A class declares fields (data) and methods (behavior); new creates objects from it.
  • Use the dot operator: obj.field, obj.method().
  • Each object has its own copy of the instance variables, and fields get default values.
  • Variables of class types hold references. Assigning copies the reference, == compares references, and null means no object.

Next lesson: constructors: setting up an object's fields the moment it's created.

References and further reading