Tools
Log in
English

Learn to codeJava

Java classes and objects

Based on Java 17record · Java 16+

Java classes and objects, constructors and this, with a step-through example.

In one line

A class bundles values and actions into a template; an object is one copy made from that template with new.

Why you need it

Keeping the title, page count and pages read of three books in loose variables quickly gives you title1, pages1, read1 and so on. Adding a book means edits in several places, and it is easy to add pages to the wrong book.

Put the three values and read() in one Book class and each book becomes a single variable. One more book is one more new Book(...) line.

Everyday picture

Think of a cookie cutter and cookies. There is one cutter (the class), but you can stamp out as many cookies (objects) as you like, each with its own toppings. The constructor is the moment you press the cutter and decorate that cookie.

Example code

Main.java · 31 lines
class Book {    String title;    int pages;    int readPages;     Book(String title, int pages) {        this.title = title;        this.pages = pages;        this.readPages = 0;    }     void read(int count) {        readPages = Math.min(pages, readPages + count);    }     int percent() {        return readPages * 100 / pages;    }} public class Main {    public static void main(String[] args) {        Book novel = new Book("Small Town", 240);        Book guide = new Book("Java Basics", 120);        novel.read(60);        guide.read(30);        guide.read(500);        System.out.println(novel.title + ": " + novel.percent() + "%");        System.out.println(guide.title + ": " + guide.percent() + "%");    }}

When to use it

  • You have many records with the same shape (members, orders, books, posts)
  • You want values and the code that changes them to live together (add pages read, work out progress)
  • A noun keeps coming up when you explain the program. That noun is a class candidate.

A class that only carries values can be one line: record Point(int x, int y) {}. Java writes the constructor, accessors, equals and toString for you (Java 16+).

Common mistakes

Leaving out this. in the constructor

When the parameter has the same name as the field, title = title; only assigns the parameter to itself. The field stays null.

Wrong

class Book {    String title;     Book(String title) {        title = title;    }} public class Main {    public static void main(String[] args) {        Book b = new Book("Small Town");        System.out.println(b.title);    }}

When you run itnull

Fixed

class Book {    String title;     Book(String title) {        this.title = title;    }} public class Main {    public static void main(String[] args) {        Book b = new Book("Small Town");        System.out.println(b.title);    }}

When you run itSmall Town

Calling a method without an object

read changes the values of one book, so Java needs to know which book. Create an object with new and call the method on it.

Wrong

public class Main {    public static void main(String[] args) {        Book.read(10);    }}

What javac sayserror: non-static method read(int) cannot be referenced from a static context

Fixed

public class Main {    public static void main(String[] args) {        Book book = new Book();        book.read(10);        System.out.println(book.readPages);    }}

When you run it10

Comparing objects with ==

== asks whether both sides are the very same object. Use equals to compare contents. A record gets equals for free (Java 16+).

Wrong

record Point(int x, int y) {} public class Main {    public static void main(String[] args) {        Point a = new Point(1, 2);        Point b = new Point(1, 2);        System.out.println(a == b);    }}

When you run itfalse

Fixed

record Point(int x, int y) {} public class Main {    public static void main(String[] args) {        Point a = new Point(1, 2);        Point b = new Point(1, 2);        System.out.println(a.equals(b));    }}

When you run ittrue

Check yourself

Question 1

After a reads 40 pages, what does printing b.readPages show?

public class Main {    public static void main(String[] args) {        Book a = new Book("A", 100);        Book b = new Book("B", 100);        a.read(40);        System.out.println(b.readPages);    }}

Show the answer

Answer: 2. 0 a and b are separate objects with their own fields. a.read(40) only changes a, so b keeps its starting value 0.

Question 2

Which sentence about constructors is true?

Show the answer

Answer: 1. It runs when an object is created and sets the first values A constructor has no return type at all, and a class may have several as long as their parameters differ (constructor overloading).

Questions people ask

What is the difference between a class and an object?

A class is a blueprint written once in code. An object is a real bundle of values made with new while the program runs. One class can make any number of objects.

When must I write this?

When a parameter has the same name as a field. this.title means the field, plain title means the parameter. With different names you can leave it out.

What if I write no constructor?

Java adds a default constructor with no parameters. Once you write any constructor yourself, that default one is no longer added.