What Is an Object?
By the end of this lesson, you'll be able to:
- Define what an object (instance) is
- Create an object from a class using the new keyword
- Explain that multiple objects from the same class are independent of each other
Prerequisites: "What Is a Class?"
Creating an object with new
public class GymMember {
public String name;
public Integer age;
}
GymMember member1 = new GymMember();
member1.name = 'Zanele';
member1.age = 28;
new GymMember() builds one actual object from the GymMember blueprint, and member1 is a variable holding a reference to it. Setting member1.name and member1.age fills in that specific object's data.
Independent objects from the same class
GymMember member1 = new GymMember();
member1.name = 'Zanele';
GymMember member2 = new GymMember();
member2.name = 'Kofi';
System.debug(member1.name); // Zanele
System.debug(member2.name); // Kofi
member1 and member2 are both GymMember objects, built from the same class, but changing one never affects the other — exactly like two houses built from the same blueprint don't share walls.
Common mistakes
- Forgetting new.
GymMember member1;declares a variable that can hold aGymMember, but it starts outnull— no object exists untilnew GymMember()actually creates one. - Assuming two variables always mean two objects.
GymMember member3 = member1;doesn't create a new object —member3andmember1both point to the same object, so changing one through either variable affects both.
Exercise
Given the GymMember class above, create two GymMember objects with different names and ages, and debug both names.
Show hint
GymMember member1 = new GymMember(); member1.name = ...;
What Is an Object? Quiz
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
An object is one actual, specific thing built from a class's blueprint — created with new, and independent of every other object built from the same class.