Classes and Objects in Java
The blueprint-and-instance model at the heart of Java — defining a class and creating objects from it.
2 min read
Everything you've written so far has lived inside a class, but only as static methods called directly on the class itself. Most real Java programs instead model the world as objects — individual instances of a class, each with its own state. This is the shift from "a class with utility methods" to true object-oriented design.
Defining a class
A class is a blueprint: it describes what fields (data) and methods (behavior) its objects will have, without creating any objects itself.
public class Dog {
String name;
int age;
void bark() {
System.out.println(name + " says Woof!");
}
}Dog describes the shape of a dog — a name, an age, and the ability to bark — but writing this class alone doesn't create any actual dogs.
Creating objects with new
An object (or instance) is created from a class using new, which allocates memory and returns a reference to it:
Dog myDog = new Dog();
myDog.name = "Rex";
myDog.age = 3;
myDog.bark(); // Rex says Woof!
Dog anotherDog = new Dog();
anotherDog.name = "Fido";
anotherDog.bark(); // Fido says Woof!myDog and anotherDog are two completely independent objects, each with its own name and age. Changing myDog.name has no effect on anotherDog — this independent state per object is the entire point of instances.
Instance vs. static members
A field or method without static belongs to each individual object (an instance member); one marked static belongs to the class itself, shared across every instance.
public class Dog {
String name; // instance field: each dog has its own
static int totalDogs = 0; // static field: shared by all dogs
Dog(String name) {
this.name = name;
totalDogs++;
}
}totalDogs is incremented every time a Dog is created, and every Dog object sees the same value, because there's only ever one copy of it — unlike name, which each object holds separately.
The this keyword
Inside an instance method or constructor, this refers to the current object — the one the method was called on. It's most commonly used, as above, to distinguish a field from a parameter that happens to share its name (this.name = name; — "set this object's name field to the parameter named name").
Classes and objects are the foundation everything else in object-oriented Java builds on: constructors, inheritance, interfaces, and encapsulation all exist to make defining and using classes safer and more expressive.
Test what you just learned
4 quick questions. Get all of them right to unlock the next lesson.
You can take the quiz without an account — logging in just lets your result count toward your progress.