16. Class vs Object
A class is a blueprint; an object is an instance of that blueprint created at runtime. Reference variables hold memory addresses (references), not the objects themselves.
Java 21 (core language)Explanation
A class defines structure (fields) and behaviour (methods). An object (instance) is a specific, live chunk of heap memory created from that blueprint by new. Multiple objects of the same class share the class definition but have independent field values.
Reference types in Java: all class instances, arrays, and interfaces are reference types. A reference variable holds the memory address of the object, not the object itself. When you write Dog d = new Dog(), d is a reference (like a pointer) stored on the stack (or in a field), while the Dog object lives on the heap.
Null is the absence of a reference โ a reference variable not pointing at any object. Attempting to dereference null (null.method()) throws a NullPointerException. Fields of reference type default to null; primitive fields default to 0/false.
Example
public class ClassVsObject {
// Class blueprint
static class Dog {
String name; // reference field โ default null
int age; // primitive field โ default 0
Dog(String name, int age) {
this.name = name;
this.age = age;
}
void bark() { System.out.println(name + ": Woof!"); }
}
public static void main(String[] args) {
// Two distinct objects from the same class
Dog rex = new Dog("Rex", 3);
Dog bella = new Dog("Bella", 5);
rex.bark(); // Rex: Woof!
bella.bark(); // Bella: Woof!
// Reference assignment: both point to the SAME object
Dog alias = rex;
alias.name = "Max";
System.out.println(rex.name); // "Max" โ same object mutated
// null reference
Dog nobody = null;
System.out.println(nobody); // null
try {
nobody.bark(); // NullPointerException!
} catch (NullPointerException e) {
System.out.println("NPE: cannot call method on null reference");
}
// instanceof check (good practice before casting)
Object obj = rex;
if (obj instanceof Dog d) {
System.out.println("It's a dog named " + d.name);
}
}
}Sources
- https://docs.oracle.com/javase/tutorial/java/javaOO/classes.html โ Classes tutorial
- https://docs.oracle.com/javase/tutorial/java/javaOO/objectcreation.html โ Creating objects