Classes and Objects
How a class becomes an object, and why a variable holds a reference rather than the object itself.
Open this lesson in the learning hubKey points
- A class is the blueprint. An object is one thing built from it.
newbuilds one and hands you a reference. - Fields hold state, methods hold behaviour. Keeping the two together is the whole idea of object orientation.
- Variables never hold objects, only references.
a = bcopies the arrow, not the thing it points at. ==asks "is this the same object?" It does not ask "do these look alike?" That question isequals.- Objects live on the heap. The garbage collector frees them once nothing references them, so there is no delete.
Example
public class Main {
// A class is a blueprint. Every 'new' builds one object on the heap.
static class Dog {
String name;
int age;
void bark() {
System.out.println(name + " says woof");
}
}
public static void main(String[] args) {
Dog rex = new Dog();
rex.name = "Rex";
rex.age = 3;
rex.bark();
Dog alias = rex; // copies the reference, NOT the object
alias.age = 4;
System.out.println("rex.age = " + rex.age);
System.out.println("same? = " + (rex == alias));
Dog bella = new Dog();
bella.name = "Bella";
System.out.println("same? = " + (rex == bella));
}
}
A class is a blueprint; a variable holds a reference, never the object itself.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the OOP course, and every lesson in it is listed on the OOP contents page.