Skip to content
Tutorials Center
My learning

Topics

Lesson 47 of 201 ยท Object-Oriented Programming

Classes and Objects

Learn to define Java classes, create objects with new, understand references and aliasing, null and NullPointerException, several classes in one file and objects in memory.

In the previous lesson you saw why Java organizes programs around objects. Now it's time to build them yourself. A class declares a new type: once you've written class Book { ... }, Book is a type just like String or int, and you can declare variables, parameters, arrays and lists of it.

This lesson covers the mechanics every Java programmer must know cold: how to declare a class, how new creates an object, what a reference is (and why b = a doesn't copy an object), what null means, how objects behave when passed to methods, and where they live in memory. These rules explain a huge share of real-world bugs, so take your time with the examples.

Declaring a class

The simplest useful class just groups related data. Each variable declared directly inside the class (not inside a method) is a field:

Java
class Book {
    String title;
    String author;
    int pages;
    boolean borrowed;
}

That's a complete class. It declares a type named Book; every Book object will have its own title, author, pages and borrowed. Class names use PascalCase (Book, ShoppingCart, HttpClient) and are usually nouns. Fields and methods use camelCase.

Creating objects with new

A class by itself does nothing; it's a description. To get an actual book, you instantiate the class with new:

Java Creating and using objects

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

new Book() does three things:

  1. Allocates memory for a new Book object on the heap, with room for all its fields.
  2. Initializes every field to its default value: null for references like String, 0 for numbers, false for boolean. That's why the first line prints null, 0, false.
  3. Runs a constructor (here the invisible default one) and gives you back a reference to the new object.

You access fields with the dot operator: first.title. Setting fields one by one after new is clumsy and easy to forget, which is exactly the problem constructors solve. Fields and their defaults get a closer look in Fields and Instance Methods.

Variables hold references, not objects

This is the single most important idea in the lesson. A variable of a class type doesn't contain the object. It contains a reference: a pointer-like value that says where the object lives. Think of the object as a house and the reference as its address written on a card.

So assigning one variable to another copies the address, not the house:

Java Two references, one object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

After Book b = a; there is still only one book, with two variables referring to it. Changing it through b is visible through a. Two references to the same object are called aliases.

The == operator on references asks "do these point to the same object?" (identity), not "do they hold equal data?". a == c is false even though both books have the same title, because they're two separate objects. To compare contents you use equals, which classes like String define meaningfully; for your own classes you'll learn to write it in The Object Class: equals, hashCode and toString.

Primitives (int, double, boolean, ...) work differently: the variable holds the value itself, so int y = x; copies the number, and changing y never affects x. Only class types (and arrays) are references. See Primitive Data Types.

null: a reference to nothing

A reference variable can also hold the special value null, meaning "no object". Fields of class types start as null, and you can assign it yourself:

Java
Book favorite = null;      // no book chosen yet

Using the dot operator on null has no object to work with, so Java throws NullPointerException (NPE). This example crashes on purpose:

Java NullPointerException with a helpful message

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The output shows the program's first two lines, then a stack trace. Since Java 14, NPE messages tell you exactly what was null, here Cannot invoke "String.length()" because "<local1>.title" is null. (The single-file launcher compiles without local variable names, so it says <local1> instead of book; in an IDE build you'd see "book.title".) The fix is to make sure fields get real values, ideally in a constructor, or to check for null before use.

Printing or concatenating null is fine ("title is " + null gives "title is null"). It's calling a method or reading a field through null that fails.

Objects and methods

When you pass an object to a method, Java copies the reference into the parameter (Java is always pass-by-value; for objects, the value is the reference). Both the caller and the method now point to the same object, so:

  • changes the method makes to the object are visible to the caller;
  • reassigning the parameter to a new object only changes the method's local copy.
Java What a method can and can't change

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

addAppendix modified the caller's book. replace built a new book and pointed its own parameter at it, which the caller never sees. If a method should produce a new object, return it. This is covered in more depth in Parameters and Return Values.

Several classes in one file

You've been writing several classes in one file all along. The rules:

  • A file may contain any number of top-level classes, but at most one of them can be public.
  • If there's a public class, the file must be named after it: public class Main goes in Main.java.
  • The compiler produces one .class file per class (Main.class, Book.class), whatever file they came from.

In real projects, the convention is one top-level class per file, each named after its class, organized into packages (Packages and Imports). Putting small helper classes next to Main, as these lessons do, is fine for examples and scripts. When you run a single file with java Main.java, the first class declared is the one whose main method runs.

Classes can be used before they're declared in the file; order doesn't matter to the compiler.

Arrays and lists of objects

Because a class is a type, you can make arrays and collections of it. An array of objects is an array of references, and every slot starts as null until you put an object there:

Java An array of objects and default toString

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Two things to notice:

  • new Book[3] creates an array, not three books. Forgetting the loop that fills it is a classic source of NullPointerException.
  • Printing an object shows something like Book@1b6d3586: the class name and a hash code, because Book doesn't define toString() yet. You'll fix that in The Object Class; records generate a readable one automatically.

Objects in memory

A simplified picture of what the JVM does:

  • Local variables (including parameters and references like book) live in the current method's stack frame and disappear when the method returns.
  • Objects live on the heap, a large shared memory area. new always creates the object on the heap.
  • A reference on the stack points to an object on the heap; objects' fields can point to other objects, forming a graph.
TEXT
 stack (main's frame)            heap
 +-----------------+
 | a  -------------+------>  Book { title -> "Changed through b" }
 | b  -------------+
 | c  -------------------->  Book { title -> "Changed through b" }
 +-----------------+

That's the memory picture for the "Two references, one object" example: a and b share one object, and c points to another.

You never free objects yourself. When no reference leads to an object anymore, it becomes unreachable, and the garbage collector reclaims its memory at some later point. Setting a variable to another object or to null, or returning from the method that held the only reference, can make an object unreachable. The details, and how memory leaks still happen in Java, are in Memory and Garbage Collection.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this print? Book x = new Book(); x.pages = 10; Book y = x; y.pages = 50; System.out.println(x.pages);

    y = x copies the reference, so both variables point to the same Book. Changing it through y is visible through x.
  2. 2. After Book[] shelf = new Book[4];, how many Book objects exist?

    The array holds four references, all null. No Book objects exist until you create them with new Book().
  3. 3. Two separate Book objects both have title "Dune". What does a == b evaluate to?

    For references, == compares identity (same object), not contents. Use equals to compare data, once the class defines it.
  4. 4. A method void reset(Book b) { b = new Book(); } is called as reset(myBook). What happens to myBook?

    The parameter is a copy of the reference. Reassigning the copy points it at a new object, but the caller's variable is unchanged.
  5. 5. A Book has a String title field that was never set. What does book.title.length() do?

    Reference fields default to null, and calling a method through null throws NullPointerException.

Summary

  • A class declares a new type; its fields describe the data every object of that type carries.
  • new ClassName() allocates an object on the heap, sets fields to default values (null, 0, false) and returns a reference to it.
  • Variables of class types hold references: assignment copies the reference, creating aliases; == compares identity, not contents.
  • null means "no object"; reading a field or calling a method through null throws NullPointerException.
  • Methods receive a copy of the reference: they can change the object, but reassigning the parameter doesn't affect the caller.
  • A file can hold many classes but at most one public one, named after the file; arrays of objects start full of null.
  • Unreachable objects are reclaimed by the garbage collector.

Next: Fields and Instance Methods, where you'll give objects behavior and learn how methods work with an object's state.