Skip to content
Laviyx Learn

Try

Java course menu

Java Classes and Objects: Fields, Methods, new and this

Learn Java classes and objects: defining a class with fields and methods, creating objects with new, references and null, instance vs static members, the this keyword, toString, and how objects behave when assigned and compared.

Intermediate12 min readUpdated
On this page

Java is an object-oriented language: programs are built from objects that combine data (what they know) with behaviour (what they can do). A class is the blueprint; an object (or instance) is one thing built from it. A BankAccount class describes what every account has and does; your account and mine are two objects of that class.

A first class#

Java
class BankAccount {
    String owner;
    double balance;

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

    void print() {
        System.out.println(owner + ": " + balance);
    }
}

public class Main {
    public static void main(String[] args) {
        BankAccount a = new BankAccount();
        a.owner = "Asha";
        a.deposit(500);

        BankAccount b = new BankAccount();
        b.owner = "Ravi";
        b.deposit(1200);
        b.deposit(300);

        a.print();
        b.print();
    }
}
Output
Asha: 500.0
Ravi: 1500.0
  • Fields (owner, balance) hold each object's data. Every object has its own copy.
  • Methods (deposit, print) act on the object they are called on. Inside them, balance means this object's balance.
  • new BankAccount() creates an object; the variable a holds a reference to it.
  • Use the dot to reach members: a.deposit(500).

Several classes can live in one file, but only one can be public, and it must match the file name. In real projects, each class usually gets its own file.

Default field values#

Fields that you do not initialize get default values: 0 for numbers, false for boolean, and null for references. (Local variables, in contrast, must be initialized before use.) Above, balance starts at 0.0 and owner at null.

Instance methods vs static methods#

The methods in BankAccount have no static keyword, so they are instance methods: you call them on an object (a.deposit(...)). A static method belongs to the class and is called on the class name (Math.max(...)). An instance method can use the object's fields; a static method cannot, because it has no object. See Scope and static.

Objects are references#

A variable of a class type holds a reference, not the object itself. Assigning it copies the reference, so both variables refer to the same object:

Java
class Counter {
    int value;
}

public class Main {
    public static void main(String[] args) {
        Counter c1 = new Counter();
        Counter c2 = c1;        // same object, two names
        c2.value = 10;
        System.out.println(c1.value);

        Counter c3 = new Counter();
        System.out.println(c1 == c2);   // same object?
        System.out.println(c1 == c3);
    }
}
Output
10
true
false

== compares references. To compare objects by their contents, a class overrides equals (records do this automatically; see Records and Enums).

null#

A reference variable that refers to no object holds null. Calling a method on null throws a NullPointerException:

Java
class Pet {
    String name = "Bruno";
}

public class Main {
    public static void main(String[] args) {
        Pet pet = null;
        try {
            System.out.println(pet.name);
        } catch (NullPointerException e) {
            System.out.println("pet is null");
        }
        pet = new Pet();
        System.out.println(pet.name);
    }
}
Output
pet is null
Bruno

The this keyword#

Inside an instance method, this refers to the current object. It is mainly used when a parameter has the same name as a field, and to return the object itself for method chaining:

Java
class Message {
    private StringBuilder text = new StringBuilder();

    Message add(String part) {
        this.text.append(part);
        return this;   // return the same object
    }

    String text() {
        return text.toString();
    }
}

public class Main {
    public static void main(String[] args) {
        Message m = new Message();
        m.add("Hello").add(", ").add("Java");
        System.out.println(m.text());
    }
}
Output
Hello, Java

toString: a readable description#

Printing an object calls its toString() method. The default prints something like BankAccount@1b6d3586. Overriding it makes objects easy to print and debug:

Java
class Point {
    int x;
    int y;

    @Override
    public String toString() {
        return "(" + x + ", " + y + ")";
    }
}

public class Main {
    public static void main(String[] args) {
        Point p = new Point();
        p.x = 3;
        p.y = 4;
        System.out.println(p);
        System.out.println("Point: " + p);
    }
}
Output
(3, 4)
Point: (3, 4)

@Override asks the compiler to check that the method really overrides one from a parent class (here Object, the root of every class).

Objects in collections#

Java
import java.util.ArrayList;
import java.util.List;

class Item {
    String name;
    double price;

    Item(String name, double price) {
        this.name = name;
        this.price = price;
    }
}

public class Main {
    public static void main(String[] args) {
        List<Item> cart = new ArrayList<>();
        cart.add(new Item("Pen", 25));
        cart.add(new Item("Notebook", 60));
        cart.add(new Item("Bag", 799));

        double total = 0;
        for (Item item : cart) {
            total += item.price;
        }
        System.out.println(cart.size() + " items, total " + total);
    }
}
Output
3 items, total 884.0

Item(String name, double price) is a constructor, which sets up a new object. It is the topic of Constructors. Here the fields are still accessible from outside the class; Encapsulation shows how to protect them.

Common mistakes#

Practice#

Practice exercise

Write a class Rectangle with width and height fields and methods area() and perimeter(), plus a toString() returning Rectangle 4.0x2.5. Create one, set its fields, and print it with its area and perimeter.

Show solution
Java
class Rectangle {
    double width;
    double height;

    double area() {
        return width * height;
    }

    double perimeter() {
        return 2 * (width + height);
    }

    @Override
    public String toString() {
        return "Rectangle " + width + "x" + height;
    }
}

public class Shapes {
    public static void main(String[] args) {
        Rectangle r = new Rectangle();
        r.width = 4;
        r.height = 2.5;
        System.out.println(r + ": area " + r.area() + ", perimeter " + r.perimeter());
    }
}
Output
Rectangle 4.0x2.5: area 10.0, perimeter 13.0

Key takeaway#

Finished this lesson?