Classes and Objects in Java
A class is a blueprint describing what data (fields) and behavior (methods) its instances will have; an object is one actual instance of that blueprint, created with new, with its own independent copy of every field the class declares. Two objects of the same class share the same structure — the same fields, the same methods — but each has entirely separate field values, so changing one object's data never affects another.
Everything in Java lives inside some class, even the simple programs seen so far, but those classes only had static members, meant to be used without ever creating an object. Most real Java code instead centers on defining classes specifically to be instantiated many times, each instance representing one distinct thing: one Dog, one BankAccount, one User.
A class is a blueprint
It declares what fields and methods every instance of it will have, without itself holding any actual data.
An object is an instance
Created with new ClassName(), each object gets its own independent copy of every field the class declares.
Shared structure, separate data
Two objects of the same class run the exact same methods, but each has its own field values, changed independently.
Creating an object
new Dog() allocates memory for a new Dog instance and runs its constructor to initialize it.
Accessing fields and methods
Dot notation, like myDog.bark(), reaches a specific object's own field or method.
public class Dog { String name; void bark() { System.out.println(name + " says Woof!"); } public static void main(String[] args) { Dog first = new Dog(); first.name = "Rex"; Dog second = new Dog(); second.name = "Fido"; first.bark(); second.bark(); }}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Java yourself — building beats watching.