Skip to content
Codescope

Classes & instances

Fields per object, methods shared, constructors chained.

intro8 min5 steps

Before you start

A **class** is a blueprint. An **instance** is a house built from that blueprint. The class describes what fields and methods exist; each instance is a separate object on the heap with its own field values.

The **constructor** is the code that runs when you call new — it sets up the fresh object's fields. And static marks something as belonging to the class itself, not to any one instance: one copy total, shared by everyone.

This lesson creates two Dog objects, watches each one get its own name and age, and shows a static counter shared between them.

Stack

references on the stack
main()
aDog
ref

Heap

each object has its own fields
Dogjust created
nameString
Rex
ageint
3

Dog.class

shared across all instances
static
countint
1

One object on the heap. count is 1 — shared across all Dogs.

Step 1 of 5. new allocates and calls the constructor. `new Dog("Rex", 3)` does two things: allocates space on the heap for a Dog object, then calls the constructor to fill in its fields. The constructor also increments `count`, which is a `static` field — it belongs to the class, not to any one object.

01 / 05

Step 01 / 05

new allocates and calls the constructor

new Dog("Rex", 3) does two things: allocates space on the heap for a Dog object, then calls the constructor to fill in its fields.

The constructor also increments count, which is a static field — it belongs to the class, not to any one object.

classes-and-instances.javaJava
public class Dog {    String name;       // instance field — per object    int    age;        // instance field — per object    static int count;  // class field — one copy total    Dog(String name, int age) {        this.name = name;        this.age  = age;        count++;    }    String greet() {          // instance method        return "I'm " + name;    }    static int getCount() {   // static method        return count;          // cannot access 'name' here    }}Dog a = new Dog("Rex", 3);   // count → 1Dog b = new Dog("Luna", 5);  // count → 2a.greet();                    // "I'm Rex"Dog.getCount();               // 2