thecodex.expert · The Codex Family of Knowledge
Java

Classes and Objects

Every object created with new gets its own separate copy of each instance field — but every object of the same class shares exactly one copy of each static field.

Java 21 LTS static = class, not instance Last verified:
Canonical Definition

A class is a blueprint declaring fields (state) and methods (behavior); new allocates an actual object on the heap following that blueprint, running a constructor to initialize it. this, used inside an instance method or constructor, refers to the current object — commonly needed to disambiguate a constructor parameter from a field of the same name. static fields and methods belong to the class itself, shared by every instance, rather than being duplicated per object.

Declaring a class and creating objects

A constructor shares the class's exact name and has no return type at all — not even void. Each call to new allocates a distinct object with its own copy of every instance field.

JavaPerson.java
public class Person {
    String name;    // instance field
    int age;

    public Person(String name, int age) {   // constructor
        this.name = name;   // this.name is the field; name is the parameter
        this.age = age;
    }
}

Person alice = new Person("Alice", 30);
Person bob = new Person("Bob", 25);
// alice and bob each have their OWN separate name and age

this: referring to the current object

this is most commonly needed when a parameter's name shadows a field's name, but it's also used to call another constructor in the same class (this(...)) or to pass the current object as an argument.

JavaConstructors.java
public class Rectangle {
    int width, height;

    public Rectangle(int width, int height) {
        this.width = width;
        this.height = height;
    }

    public Rectangle(int side) {
        this(side, side);   // calls the two-arg constructor above — a square
    }
}

static: belongs to the class, not any one object

All instances share exactly one copy of a static field — changing it through one object's reference is visible through every other reference too, since there's genuinely only one copy in memory.

JavaCounter.java
public class Counter {
    static int totalCreated = 0;   // ONE copy, shared by every instance

    public Counter() {
        totalCreated++;
    }
}

new Counter();
new Counter();
new Counter();
System.out.println(Counter.totalCreated);   // 3 — accessed via the CLASS, not an instance

Sources

1
Oracle. The Java Tutorials, "Classes" and "Understanding Class Members," docs.oracle.com/javase/tutorial/java/javaOO.