Explain it simply
Explain it simply
Picture a class as the blueprint in a car factory. The blueprint says "every car has a colour and a model, and can be driven", but you cannot drive the blueprint. An object is an actual car built from it: a red Mustang, a blue Civic, and so on.
Just as important: a variable is not the car itself but more like a car key. Writing Car sameCar = myCar; does not build a new car; it cuts a second key for the same car. Repaint the car using one key and you will see the new colour when you open it with the other.
Problem → Why → Solution
The problem: calling an instance method without an object
As soon as the Car class exists, it is tempting to call Car.drive() directly. The compiler refuses with "non-static method drive() cannot be referenced from a static context". drive() prints a colour and a model, but whose colour? The blueprint has no colour; only individual cars do.
public class Main {
public static void main(String[] args) {
Car.drive(); // error: non-static method drive() cannot be referenced
// from a static context
}
}
class Car {
String color;
String model;
void drive() {
System.out.println(color + " " + model + " is driving.");
}
}Why is an object required?
Fields and methods without static belong to each individual object. The color inside drive() really means this.color, "the colour of the object this method was called on". Only after Car myCar = new Car(); and a call like myCar.drive() does this become myCar, so Java knows where to read color from.
Core concept: what new does and what a variable holds
A class declaration describes a new type: which fields every object will have and which methods can be called on it. When new Car() runs, Java does three things. First it reserves space for the fields on the heap. Second it gives every field a default value: 0 for numbers, false for boolean, and null for reference types such as String. Third it hands back a reference to where the object lives.
In Car myCar = new Car(); the variable myCar stores that reference, not the object. So Car sameCar = myCar; copies only the reference, and both variables point at the same single object. This is called aliasing. Change color through sameCar and reading it through myCar shows the change, because there is only one object.
For reference types, == checks identity: "do these point at the same object?" Two cars with identical fields, myCar and twin, are not == because new ran twice and produced two objects. To compare contents you use equals(), and for your own class the version inherited from Object also just checks identity unless you override it.
Inside an instance method, a bare field name such as color is read as this.color, where this is the reference to the object the method was called on. That is how one piece of method code produces different results for every object.
Once no variable refers to an object any more, for example after myCar = null; with no alias left, the program has no way to reach it again. The JVM's garbage collector then reclaims that object's memory automatically, which is why Java has no free() call like C. An object's lifetime runs from new until its last reference disappears.
- new builds an object on the heap
- Fields start as 0, false or null
- The variable stores a reference
- = copies the key, never the car
== asks whether two keys open the same car, not whether two cars look alike.
General pattern
class ClassName {
Type fieldName; // one copy per object
ReturnType methodName() { // instance method
return ...fieldName...; // same as this.fieldName
}
}
ClassName ref = new ClassName(); // create + store reference
ClassName alias = ref; // same object, second reference
boolean same = (ref == alias); // identity check: truenew ClassName() creates a new object and returns a reference to it. Assigning that reference to another variable creates an alias, not a copy. == compares references, asking whether they point to one object.
Example: one car, two keys
This example creates an object, sets its fields and calls a method, then tests aliasing directly. Before running it, predict what myCar.drive() prints after the colour is changed through sameCar, and what the two == checks show.
public class Main {
public static void main(String[] args) {
Car myCar = new Car();
myCar.color = "Red";
myCar.model = "Mustang";
myCar.drive();
Car sameCar = myCar; // copies the reference, not the car
sameCar.color = "Blue";
myCar.drive();
Car twin = new Car();
twin.color = "Blue";
twin.model = "Mustang";
System.out.println("myCar == sameCar: " + (myCar == sameCar));
System.out.println("myCar == twin: " + (myCar == twin));
}
}
class Car {
String color;
String model;
void drive() {
System.out.println(color + " " + model + " is driving.");
}
}Code breakdown
- Building the object
Car myCar = new Car();At this moment color and model are still null; calling drive() right away would print "null null is driving.".
- Aliasing
Car sameCar = myCar; // copies the reference, not the carThere is no new, so no object is created. sameCar and myCar now point at the same object.
- Change through the alias
sameCar.color = "Blue";This changes the one shared object, so the following myCar.drive() prints "Blue Mustang is driving.".
- Identity vs content
System.out.println("myCar == twin: " + (myCar == twin));twin has the same colour and model, but it was built by a separate new, so == is false. == compares identity, not contents.
- Implicit this
System.out.println(color + " " + model + " is driving.");This color means this.color. For myCar.drive(), this is myCar, so myCar's fields are read.
Red Mustang is driving.
Blue Mustang is driving.
myCar == sameCar: true
myCar == twin: falseDefault values, and equals() on a record
For data classes that should be equal whenever their contents match, Java 16 and later offer records. A record automatically gets an equals() and hashCode() that compare its components, plus a readable toString(). In the code below, p1 and p2 are two objects, so == is false, yet equals() is true. The Box class never assigns its fields, so it shows the default values.
public class Main {
public static void main(String[] args) {
Point p1 = new Point(3, 4);
Point p2 = new Point(3, 4);
System.out.println(p1);
System.out.println("p1 == p2: " + (p1 == p2));
System.out.println("p1.equals(p2): " + p1.equals(p2));
System.out.println("distance: " + p1.distanceFromOrigin());
Box empty = new Box();
System.out.println(empty.label + " " + empty.count + " " + empty.open);
}
}
record Point(int x, int y) {
double distanceFromOrigin() {
return Math.sqrt(x * x + y * y);
}
}
class Box {
String label;
int count;
boolean open;
}| Field type | Default value |
|---|---|
| int, long, double and other numbers | 0 or 0.0 |
| boolean | false |
| String, arrays, any class type | null |
Local variables get no default
Defaults apply only to fields. Using a local variable without assigning it first, as in Car c; c.drive(); inside a method, is the compile error "variable c might not have been initialized".
In real projects
Where this shows up in real projects
Every business application has classes such as Product, Customer, Invoice and BlogPost, and creates thousands of objects per request. Understanding aliasing matters here. If you change the price of a Product object in a cart to apply a discount, every other place that references that object, the catalogue, a wishlist, sees the new price too, because it is the very same object.
That is why teams prefer creating a new copy, or using immutable types such as records, over editing shared objects in place. Equality matters too: HashMap and HashSet look keys up with equals() and hashCode(), so a class without them used as a key will never be found again with a new object that has the same contents. In unit tests, assertEquals() also relies on equals().
Common mistakes
Common mistakes
1. Believing = copies the object
Writing Car backup = myCar; then myCar.color = "Green"; and expecting backup to stay Red. backup is an alias, so it is Green too. For a real copy, create a new object and copy the fields across.
2. Comparing object contents with ==
if (car1 == car2) does not compare fields. The same goes for Strings, and it is even more dangerous there because name == "Aung" is true in some situations and false in others. Use equals() to compare contents, and consider a record for your own data classes.
3. Calling a method through a null reference
A field declared as Car spare; with no new is null, and spare.drive() throws a NullPointerException at runtime. Make sure an object is created before the field is used.
Best practices
Best practices
- Name variables after the object's role (customerCar says more than car1).
- When several places share one object, decide which of them is allowed to modify it.
- Prefer a record for data classes that should be equal by content; if you write equals() yourself, write hashCode() with it.
Mini challenge
Mini challenge: track reading progress
Write a Book class and create two books. Keep reading one of them through an alias and show that the progress appears on the original object.
- Fields: String title, int totalPages, int pagesRead
- read(int pages) increases pagesRead but never past totalPages
- percent() returns the percentage read as an int
- printProgress() prints a line like "The Hobbit: 150/300 (50%)"
- Create an alias with Book onLoan = novel; and call onLoan.read(60)
public class Main {
public static void main(String[] args) {
// TODO: novel = "The Hobbit" (300 pages), manual = "Java Guide" (120 pages)
// TODO: novel reads 90 pages, manual reads 200 pages
// TODO: Book onLoan = novel; then onLoan reads 60 pages
// TODO: print progress for both books and whether onLoan == novel
}
}
class Book {
// TODO: fields title, totalPages, pagesRead
void read(int pages) {
// TODO: add pages, capped at totalPages
}
int percent() {
// TODO: pagesRead as a whole-number percentage of totalPages
}
void printProgress() {
// TODO: "<title>: <read>/<total> (<percent>%)"
}
}Expected: The Hobbit: 150/300 (50%) Java Guide: 120/120 (100%) onLoan is novel: true
Show hint
In read(), use Math.min(totalPages, pagesRead + pages). In percent(), multiply first, pagesRead * 100 / totalPages; pagesRead / totalPages * 100 gives 0 because of integer division.
Show solution
public class Main {
public static void main(String[] args) {
Book novel = new Book();
novel.title = "The Hobbit";
novel.totalPages = 300;
Book manual = new Book();
manual.title = "Java Guide";
manual.totalPages = 120;
novel.read(90);
manual.read(200);
Book onLoan = novel;
onLoan.read(60);
novel.printProgress();
manual.printProgress();
System.out.println("onLoan is novel: " + (onLoan == novel));
}
}
class Book {
String title;
int totalPages;
int pagesRead;
void read(int pages) {
pagesRead = Math.min(totalPages, pagesRead + pages);
}
int percent() {
return pagesRead * 100 / totalPages;
}
void printProgress() {
String pages = pagesRead + "/" + totalPages;
System.out.println(title + ": " + pages + " (" + percent() + "%)");
}
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A class is a type and a template; an object is an instance created with new.
- new starts fields at 0, false or null and returns a reference to the object.
- Variables hold references, so = creates an alias and never duplicates the object.
- == checks identity; comparing contents needs equals() (or a record).
- Instance methods are called on an object, and a bare field name inside them means this.field.