How to create classes and objects

Define a class

Fields hold object state and methods describe behavior.

class Dog {
    String name;

    void bark() {
        System.out.println(name + " says woof!");
    }
}

Create an object

The new operator creates an instance. Dot notation accesses its fields and methods.

Dog dog = new Dog();
dog.name = "Milo";
dog.bark();

Create independent instances

Each object has its own field values even though all instances share the same class definition.

Dog first = new Dog();
first.name = "Milo";
Dog second = new Dog();
second.name = "Luna";

Separate responsibilities

A class should represent a focused concept. Keep its state valid and put behavior near the data it uses.