Java OOP · Module 2
Creating objects with new
What really happens on the right-hand side
What you'll be able to do
- List the four things `new` does, in order
- Create objects and call methods that change their state over time
- Explain why a declared-but-not-created variable throws NullPointerException
- Track an object's state through a sequence of method calls
Creating Objects (new)
The new keyword, step by step
`new Student()` looks like one action. It is actually four.
What Java does when it reads `Student s = new Student();`
- Allocates memory on the heap big enough for all of Student's fields.
- Fills every field with its type default: 0, 0.0, false, null.
- Runs the constructor (Module 3). Right now that is the invisible default constructor, which does nothing extra.
- Returns the reference — the object's address — which is stored in the variable
s.
Reading the declaration properly
=: the declared type and the variable. Right of =: the object being built. The variable is not the object — it points at it.introduce, name means this object's name — "Sara".Declaration is not creation
Student s; creates a variable holding null. The first s.name or s.introduce() then throws NullPointerException at runtime. If you see that exception, look for a missing new.
Prove it — coding challenges
Object State
State evolves through method calls
An object is not a snapshot; it has a lifetime. Every call can move it to a new state, and the next call sees the result of the previous one. Reading code therefore means tracking state, not just reading lines. Keep a small table in your head (or on paper): after each call, what does every field hold?
Before running: what will `show()` print each time? Then add one more `increment()` and re-check.
Heap after three increments
The variable never changed — only the object it points at did.
Common mistakes
Counter c; c.increment();new Counter(); c.increment();Expecting `new` to copy an existing object.Lesson playground
A lamp that toggles. Add a `brightness` field and a method that raises it, then print both fields.
Check understanding
Quiz
Question 1 of 4
Track the boolean field through three prints.
Summary
- `new` allocates, defaults every field, runs the constructor, and returns a reference.
- The variable holds a reference; the object lives on the heap.
- Missing `new` → NullPointerException as soon as you use the dot on a method.
- Reading object code means tracking state call by call.