Java Creating Objects
Table of Contents + β
In the last lesson you learned about Java creating classes. A blueprint on its own does nothing. You build a real thing from it, and that real thing is an object.
π€ Why we need to create objects
A class is like a cookie cutter. You cannot eat the cutter. It only describes a cookie. To get something real, you press it into dough. A class works the same way. Here is a small Student class.
class Student { String name; int age;}Right now no student exists.
- The class is only a plan: βa Student has a name and an ageβ.
- No name or age is stored anywhere yet.
- To get a real student with real values, you build one from the plan.
- Building a real thing from a class is called creating an object.
π Creating an object with new
To build an object, use the new keyword, the class name, and round brackets.
- An object is also called an instance. The two words mean the same thing.
- This program builds one Student object and stores its name and age.
public class Main {
public static void main(String[] args) { Student s1 = new Student(); // β
build a Student object s1.name = "Alex"; // set its name field s1.age = 20; // set its age field
System.out.println(s1.name + " is " + s1.age + " years old."); }}
class Student { String name; int age;}Line by line:
new Student()builds one real Student object in memory.Student s1 = ...makes a variables1that refers to that object.s1.name = "Alex"ands1.age = 20reach in and store values.s1.nameands1.agelater read those values back.- Now
s1is a real student, with name and age bundled as one thing.
Output
Alex is 20 years old.That first line has two halves. Student s1 declares a variable that can refer to a Student. new Student() builds the actual object. The = joins them, so s1 points at the object.
π§ The reference variable points to the heap
Many people get this wrong, so slow down here.
s1does not hold the object itself. It holds a reference to it.- The object lives in memory called the heap.
s1is a pointer to it. - Think of a house and its address: the object is the house,
s1is paper with the address. s1.namereads the address, walks to the house, and changes the name there.
This explains a result that surprises beginners: two variables can point at the same object.
public class Main {
public static void main(String[] args) { Student s1 = new Student(); s1.name = "Alex";
Student s2 = s1; // β
copies the address, NOT the object s2.name = "Riya"; // changes the one shared object
System.out.println(s1.name); // prints Riya, not Alex! }}
class Student { String name; int age;}Why s1.name prints Riya:
Student s2 = s1has nonew, so no new object is built.- It only copies the address. Both variables now hold the same address.
- They point at one single object. Change it through
s2, see it throughs1.
Output
RiyaRemember: new creates a new object. A plain = between references only copies the address.
π Reaching inside with the dot operator
The dot reaches into an object. It means βthe thing belonging to this objectβ.
s1.namereads as βthe name ofs1β.s1.agereads as βthe age ofs1β.- The dot works for methods too, not just fields.
Letβs give the class a method and call it.
public class Main {
public static void main(String[] args) { Student s1 = new Student(); s1.name = "Alex"; s1.age = 20;
s1.greet(); // β
call a method on the object }}
class Student { String name; int age;
void greet() { System.out.println("Hi, I am " + name + " and I am " + age + "."); }}Line by line:
s1.nameands1.ageuse the dot to read or set fields.s1.greet()uses the dot to call a method. The brackets mark it as a method, not a field.- Inside
greet, the bare wordnamemeans βthe name of the object it was called onβ, which iss1.
Output
Hi, I am Alex and I am 20.The dot is your one tool for everything inside an object. Fields, prints, methods. Always the same dot.
π₯ Many independent objects from one class
Now the real power.
- Each
newbuilds a brand new object on the heap. - Each object gets its own copy of the fields.
- So changing one object never touches another.
This program builds two separate students from the same class.
public class Main {
public static void main(String[] args) { Student s1 = new Student(); // first object s1.name = "Alex"; s1.age = 20;
Student s2 = new Student(); // β
a second, separate object s2.name = "Riya"; s2.age = 22;
s1.age = 21; // change ONLY s1
System.out.println(s1.name + ", " + s1.age); System.out.println(s2.name + ", " + s2.age); }}
class Student { String name; int age;}The important parts:
new Student()twice means two real objects on the heap.s1ands2hold different addresses, because eachnewmakes a fresh object.- Each object carries its own
nameandage. - We changed
s1.ageto 21, buts2.agestays 22, completely untouched.
Output
Alex, 21Riya, 22This is the whole idea: one blueprint, many independent objects. They share the shape from the class. They do not share the values.
Here is a Car class with fields and a method.
public class Main {
public static void main(String[] args) { Car car1 = new Car(); car1.brand = "Toyota"; car1.speed = 0;
Car car2 = new Car(); car2.brand = "Honda"; car2.speed = 0;
car1.accelerate(30); // speed up only car1 car2.accelerate(50); // speed up only car2 car1.accelerate(10); // car1 again
car1.show(); car2.show(); }}
class Car { String brand; int speed;
void accelerate(int amount) { speed = speed + amount; }
void show() { System.out.println(brand + " is going " + speed + " km/h"); }}Two cars from one class, sped up separately:
car1.accelerate(...)only changescar1.speed.- Inside the method,
speedmeans βthe speed of this objectβ. - Car one ends at 40, car two at 50. They never mix.
Output
Toyota is going 40 km/hHonda is going 50 km/hClass vs object, one more time
The class is written once. It is the plan. An object is created with new, and you can make as many as you like. One cutter, many cookies, each one separate. That is how one class gives you many objects, each with its own field values.
π₯ Null references and NullPointerException
A trap you will hit early: a reference that was never given an object with new.
- A reference that points at nothing has the value null.
nullmeans βthis reference points at no objectβ. The paper has no address.- Use the dot on a null reference and Java has nowhere to walk, so it stops with an error.
Watch it happen.
public class Main {
public static void main(String[] args) { Student[] students = new Student[2]; // array of references, all null // β we never did students[0] = new Student();
System.out.println(students[0].name); // boom }}
class Student { String name;}Why it breaks:
- The array holds two Student references, but we never built any objects.
- So
students[0]isnull. It points at nothing. students[0].namemeans βwalk to the object and read its nameβ, but there is no object.
NullPointerException
Exception in thread "main" java.lang.NullPointerException: Cannot read field "name" because "students[0]" is nullThis famous NullPointerException almost always means the same thing: you used the dot on a reference with no object. The fix is to build the object with new before you use it.
Student[] students = new Student[2];students[0] = new Student(); // β
now there is a real objectstudents[0].name = "Alex";
System.out.println(students[0].name); // works fineSo whenever you see NullPointerException, ask: did I forget to create the object with new?
ποΈ Class versus object, said plainly
These two words get mixed up constantly. The difference:
- A class is the blueprint, written once. It describes the fields and methods. You cannot store a value directly in it.
- An object is built from the class with
new. It lives on the heap, holds real values, and each one is independent. - In code, the class is what you write with the word
class. The object is whatnewgives back.
Both appear together here.
Student s1 = new Student();// ^^ ^^^^^^^// object classStudent on the right is the class. new Student() gives the object. s1 is a name that points to it. One class, many possible objects.
β οΈ Common Mistakes
A few object-creation slip-ups to watch for.
- Forgetting
new.Student s1;declares a variable but builds no object. The reference points at nothing.
// β no object was ever createdStudent s1;s1.name = "Alex"; // will not work, s1 has no object
// β
build the object firstStudent s1 = new Student();s1.name = "Alex";- Using a reference that is null. A reference pointing at nothing throws a
NullPointerExceptionthe moment you use a dot on it. Build the object before you touch it.
// β student is null, the dot has nowhere to goStudent student = null;System.out.println(student.name);
// β
create the object firstStudent student = new Student();student.name = "Alex";System.out.println(student.name);- Thinking objects share their fields. Each object has its own copy. Changing one does not change another.
Student s1 = new Student();Student s2 = new Student();s1.age = 20;// β thinking s2.age is now also 20 β it is not, it keeps its own value- Confusing the class with an object. The class is the blueprint. You do not store data directly on it. Create an object first, then use it.
// β trying to use the class itself as if it held dataStudent.name = "Alex";
// β
make an object, then set its fieldStudent s1 = new Student();s1.name = "Alex";β Best Practices
Good habits for creating and using objects.
- Always create with
newbefore you use. This single habit removes mostNullPointerExceptionerrors before they ever happen. - Create on the same line you declare, when you can. Writing
Student s1 = new Student();in one line means the variable is never left pointing at nothing. - Use clear variable names.
alexAccount,firstCar,s1. The name should hint at which object it points to. - Make a fresh object for each separate thing. Two students means two
new Student()calls. Do not try to reuse one object for two different people. - Remember
=copies a reference, not an object. If you truly want a second independent object, you must callnewagain.
π§© What Youβve Learned
You can now turn a blueprint into real objects. Quick recap.
- β
You build an object from a class with the new keyword, like
new Student(). - β An object lives on the heap, and the reference variable just points to it.
- β
You reach an objectβs fields and methods with the dot, like
s1.nameors1.greet(). - β
Each
newmakes a fresh, independent object, and each has its own copy of the fields. - β Changing one object never changes another, because they do not share values.
- β
A reference that points at nothing is
null, and using a dot on it throws aNullPointerException. - β The class is the one written blueprint, and objects are the many real things you build from it.
Check Your Knowledge
Test what you learned. Pick an answer for each question, then click Check.
- 1
Which keyword builds an object from a class?
Why: You use new, like new Student(), to build an object from a class.
- 2
What does the reference variable s1 actually hold?
Why: The variable holds a reference, a pointer to where the object lives on the heap, not the object itself.
- 3
After two new Student() calls, if you change s1.age, what happens to s2.age?
Why: Each new makes an independent object with its own copy of the fields, so changing one does not affect the other.
- 4
Why do you get a NullPointerException?
Why: It happens when you use the dot on a null reference, meaning no object was ever built with new.
π Whatβs Next?
You can now create objects and reach inside them with the dot. Next, look closer at what lives inside a class: data in fields, behavior in methods. There is more to know about both.