Java OOP · Module 2
Working with many objects
Arrays of objects, and objects that hold other objects
What you'll be able to do
- Create an array of objects and fill it correctly
- Loop over objects and call their behaviour
- Explain why `new Student[3]` contains no students at all
- Write a class whose job is to manage other objects
Multiple Objects
Arrays of objects: two steps, not one
`new Student[3]` creates three *slots*, not three students. Forgetting this is the classic NullPointerException.
Filling an array of objects
null. No Student exists yet.new — the array does not create anything for you.An array of objects starts full of nulls
new Student[3] then students[0].name throws NullPointerException, because slot 0 holds null. Rule of thumb: one new for the array, plus one new per element.
A class that manages other objects
Once you can hold many objects, you can write a class whose whole job is to coordinate them: a Classroom that counts passing students, a Bank that sums balances. That is your first taste of HAS-A (Module 12) and it is exactly how the final project is structured: Bank holds Account[], each Account holds a Customer.
Add a fourth student with grade 49 and re-run. Then move the `isPassing()` rule to `grade >= 60` and see the report change in one place only.
Prove it — coding challenges
Common mistakes
Student[] list = new Student[3]; list[0].name = "Sara";for (int i = 0; i <= list.length; i++)Duplicating the passing rule inside every loop that walks students.Lesson playground
A Classroom object that owns its students. Add a method that returns the highest grade.
Check understanding
Quiz
Question 1 of 4
This code throws NullPointerException on the third line. Why?
Summary
- `new Type[n]` creates n null slots; every element still needs its own `new`.
- for-each is the safest way to walk objects and call their behaviour.
- A class can hold other objects — the beginning of HAS-A design.
- Rules that depend on an object's state belong inside that object as a method.