Command Palette

Search for a command to run...

Back to the lesson: Topic 4.1 — Classes and Objects
Core Java · Example 1 of 3

Two dogs, one class

Each object has its own fields: Rex's birthday doesn't change Bella's age.

A class is a blueprint that describes what data a kind of thing holds and what it can do. An object is one real thing built from that blueprint with new, living on the heap, reached through a reference.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a class Book with fields title (String) and pages (int) and a method describe() that prints <title> has <pages> pages. Create two books and call describe() on both.

02

Write a class Counter with an int value field and a method increment(). Create two counters, increment the first three times and the second once, and print both values.

03

Create one Book, store it in two variables x and y, change pages through y, and print x.pages and x == y.

Explain it without notes

01

What is the difference between a class and an object? Use an analogy and then the precise Java terms.

02

What exactly happens, step by step, when the JVM executes Dog d = new Dog();?

03

Dog a = new Dog(); Dog b = a; b.name = "Max"; What is a.name and why?

04

Why do fields get default values while local variables must be assigned before use?

Two dogs, one class
Sign in to run this example in your browser.

Expected output

Rex says woof
Bella says woof
Rex is now 4
Bella is still 5