Objects: Instances of Classes
Why this matters
Think about your favorite role-playing game. When you start, you don't just get a generic character. You go to a character creation screen. That screen is a template, right? It has fields for a name, a class (like a warrior or a mage), hair color, and starting stats.
The game designers built one blueprint for what a character can be. But you, Maya, Carlos, and every other player use that blueprint to create your own specific character. Your character, "ShadowSlayer," is a unique instance. Maya's character, "Sunfire," is another. They were both made from the same template, but they are separate, individual entities in the game world.
That's the core idea we're exploring today: the difference between a blueprint (a class) and the actual thing you create from it (an object). We'll see how Java uses this powerful concept to build everything from simple data entries to complex game characters.
Concept overview
classDiagram
Object <|-- Vehicle
Vehicle <|-- Car
Vehicle <|-- Truck
class Object{
...
}
class Vehicle{
+int speed
+int numWheels
+startEngine()
}
class Car{
+int numDoors
}
class Truck{
+double towingCapacity
}
Core explanation
Welcome! Let's dive into the heart of object-oriented programming. It sounds complicated, but I promise it's an idea you already understand from real life.
The Blueprint and the Building
The single most important analogy for this topic is the blueprint.
Imagine an architect in Chicago designs a blueprint for a new type of eco-friendly townhouse. That blueprint is incredibly detailed. It specifies the number of bedrooms, the type of windows, the layout of the kitchen, and the materials for the roof. The blueprint itself is not a house. You can't live in a blueprint.
A class in Java is exactly like that blueprint. It's a template that defines the attributes (data) and behaviors (methods) that objects of its type will have.
class Dog {
// Attributes (the data)
String name;
String breed;
int age;
boolean isGoodBoy;
// Behaviors (the methods - what the Dog can DO)
void bark() {
System.out.println("Woof!");
}
void celebrateBirthday() {
age = age + 1;
}
}
Here, the Dog class is our blueprint. It says that any Dog we create will have a name, a breed, an age, and a good-boy status. It also says any Dog will be able to bark() and celebrateBirthday().
Now, what's an object? An object is the actual house built from the blueprint. You can take that one townhouse blueprint and build a whole neighborhood. Each house is a distinct object. They all share the same design, but each one has its own specific address, its own family living inside, and maybe a different color front door. They are instances of the blueprint.
In Java, we create an object (an "instance" of a class) using the new keyword. This process is called instantiation.
// This line creates a new Dog object from the Dog class
Dog myDog = new Dog();
Declaring Variables for Objects
Let's break that line down, because every part is important.
Dog myDog = new Dog();
Dog: This is the type. We're declaring that the variable we're about to create will refer to an object of theDogclass.myDog: This is the variable name. It's our label for the object.=: The assignment operator.new Dog(): This is the magic. Thenewkeyword tells Java's virtual machine to allocate memory for a brand newDogobject.Dog()is the constructor, a special method that creates and initializes the object. We'll talk more about constructors soon!
This covers one of our key goals: developing code to declare variables that store these kinds of objects, which are called reference types.
The Remote Control: Understanding References
When you create a variable for a primitive type like int, the variable holds the value directly.
int score = 95;
The box in memory labeled score literally contains the number 95.
Object variables work differently. The variable does not hold the object. It holds a reference to the object. Think of it as holding the memory address where the object lives.
A better analogy is a TV remote.
Dog myDog = new Dog();
The myDog variable is not the dog. It's a remote control that is tuned to the specific Dog object you just created in memory. If you want the dog to bark, you use the remote: myDog.bark().
This distinction is critical. A variable of a reference type holds an object reference, which is like the memory address of that object.
A Peek into Inheritance
Now, let's add one more layer. In the real world, we categorize things. A Golden Retriever is a specific type of Dog. A Dog is a specific type of Mammal. A Mammal is a specific type of Animal.
Java does this too, using inheritance.
We can create a general "blueprint" and then have more specific "blueprints" that inherit all the features of the general one.
- The general blueprint is called a superclass.
- The specific blueprint is called a subclass.
Let's say we have a Vehicle class. All vehicles have a speed and a number of wheels.
class Vehicle {
int speed;
int numWheels;
void go() {
// code to make it move
}
}
Now, we can create a Car class that extends Vehicle. This means it automatically gets all of Vehicle's attributes and methods, and can add its own.
// Car is a subclass of Vehicle
class Car extends Vehicle {
int numDoors; // A car-specific attribute
}
Because Car is a subclass of Vehicle, any Car object will have speed, numWheels, a go() method, and numDoors. This saves us from rewriting code and helps organize our programs logically.
Finally, a key fact to know for the AP exam: All classes in Java, whether you write it or not, are automatically subclasses of the master Object class. The Object class is the great-great-grandparent of every single object in Java. It provides some basic functionality that all objects share.
See it in action
Worked examples
Let's make this concrete. Seeing the code in action is the best way to solidify these ideas.
Example 1: Creating GamePlayer Objects
Problem: You're building a simple game. You need a way to represent players. A player has a username (a String) and a score (an int). Write the code to define a GamePlayer class and then create two distinct player objects for "Aaliyah" and "Jordan".
Solution Walkthrough:
- 1Define the Blueprint (the Class)First, we need to create the
GamePlayer.javafile. This class will define what it means to be a player.public class GamePlayer { String username; int score; }This is our blueprint. It says every
GamePlayerwill have aStringfor their name and anintfor their score. - 2Instantiate the ObjectsNow, in another file with our
mainmethod (likeGameRunner.java), we can create the actual players.public class GameRunner { public static void main(String[] args) { // Create the first player object GamePlayer player1 = new GamePlayer(); player1.username = "Aaliyah"; player1.score = 1500; // Create the second player object GamePlayer player2 = new GamePlayer(); player2.username = "Jordan"; player2.score = 1250; System.out.println("Player 1: " + player1.username + ", Score: " + player1.score); System.out.println("Player 2: " + player2.username + ", Score: " + player2.score); } }
Why it Works:
We used the GamePlayer class blueprint twice. The line GamePlayer player1 = new GamePlayer(); created the first object in memory, and the player1 variable now holds the "remote control" to it. We then used that remote (player1.username = ...) to set its specific attributes. We did the exact same thing for player2, creating a completely separate object in a different spot in memory.
The "One Remote, Two Pointers" Problem
Problem: You have one Book object. You create a second Book variable and assign the first variable to it. What happens when you change the book's title using the second variable?
Solution Walkthrough:
-
Define the
BookClass: A simple class with a title.public class Book { String title; } -
Create the Scenario: In our
mainmethod, let's run the experiment.public class Library { public static void main(String[] args) { // 1. Create ONE book object. Book favoriteBook = new Book(); favoriteBook.title = "The Great Gatsby"; // 2. Create a second variable. // This does NOT create a new object! Book bookOnLoan = favoriteBook; // 3. Let's check their titles. System.out.println("Favorite Book Title: " + favoriteBook.title); // Prints "The Great Gatsby" System.out.println("Book on Loan Title: " + bookOnLoan.title); // Prints "The Great Gatsby" // 4. Now, change the title using the second variable. bookOnLoan.title = "To Kill a Mockingbird"; // 5. What is the title of the *original* book variable now? System.out.println("Favorite Book Title after change: " + favoriteBook.title); } }
Result and Explanation:
The final line will print: Favorite Book Title after change: To Kill a Mockingbird.
Why? This is a classic AP question. The line Book bookOnLoan = favoriteBook; does not copy the object. It only copies the reference (the remote control). You now have two remotes (favoriteBook and bookOnLoan) pointing to the exact same Book object in memory. When you use one remote to change the channel (the title), anyone looking at the TV (the object) will see the change, no matter which remote they used.
Try it yourself
Ready to try on your own? Don't worry about getting it perfect; the goal is to think through the process.
-
Design a
PlaylistClass: You're building a music app. You need a class to represent a user's playlist.- What attributes would a
Playlistobject need? Think of at least two (e.g., its title, the creator's name, a list of songs). - Write the Java code for the
Playlistclass definition. - In a
mainmethod, write the single line of code that declares aPlaylistvariable namedsummerVibesand instantiates a newPlaylistobject for it.
- What attributes would a
-
Inheritance Puzzle:
- Imagine you have a
Personsuperclass. - You then create two subclasses:
StudentandTeacher. - If the
Personclass has an attributeString name, will an object created from theStudentclass have aname? Why or why not?
- Imagine you have a
Practice — 8 questions
In simple terms, a class is like a blueprint for a house, and an object is the actual, unique house you build from that blueprint.
class Dog {
// Attributes (the data)
String name;
String breed;
int age;
boolean isGoodBoy;
// Behaviors (the methods - what the Dog can DO)
void bark() {
System.out.println("Woof!");
}
void celebrateBirthday() {
age = age + 1;
}
}
- 1.12.A: Explain the relationship between a class and an object.
- 1.12.B: Develop code to declare variables to store reference types.
- 1.12.A.1
- An object is a specific instance of a class with defined attributes. A class is the formal implementation, or blueprint, of the attributes and behaviors of an object.
- 1.12.A.2
- A class hierarchy can be developed by putting common attributes and behaviors of related classes into a single class called a superclass. Classes that extend a superclass, called subclasses, can draw upon the existing attributes and behaviors of the superclass without replacing these in the code. This creates an inheritance relationship from the subclasses to the superclass.
- 1.12.A.3
- All classes in Java are subclasses of the Object class.
- 1.12.B.1
- A variable of a reference type holds an object reference, which can be thought of as the memory address of that object.
classDiagram
Object <|-- Vehicle
Vehicle <|-- Car
Vehicle <|-- Truck
class Object{
...
}
class Vehicle{
+int speed
+int numWheels
+startEngine()
}
class Car{
+int numDoors
}
class Truck{
+double towingCapacity
}
Read what Saavi narrates
(Sound of a gentle, encouraging musical intro)
Hi everyone, it's Saavi from Shrutam. Let's talk about one of the biggest ideas in all of programming, but I'll let you in on a secret… you already get it.
Think about creating a character in a video game. The game designers made a template, right? It has a spot for a name, a class, and stats. That template is the blueprint. But your character, with its unique name and skills, is a specific, individual thing.
That’s it! That's the big idea. In Java, the blueprint is called a **class**, and the individual character you create is called an **object**.
Today, we're learning how to write the code for these blueprints and how to create unique objects from them. It’s how we build everything from a simple contact list to a complex application.
Let's walk through a quick example. Imagine we need to keep track of students. First, we'd define the blueprint... the `Student` class. We'd say that every student has a name and a GPA.
Then, in our main program, we can create actual students. To create an object for a student named Priya, we might write a line like this: `Student priya = new Student();`.
That `new` keyword is the key. It tells Java, "Hey, go build me a brand new Student object based on the blueprint." The variable, which we called `priya`, doesn't hold the whole student. Think of it more like a remote control that points to the student object in the computer's memory. If we want to set her GPA, we use the remote: we'd write something like `priya.setGPA(4.0)`.
A really common mistake I see is when students declare the variable but forget to create the object. They'll write the first part, `Student priya;`, and then try to use it. But that variable isn't pointing to anything yet! It's like having a remote control with no batteries. If you try to use it, nothing happens... or in Java's case, your program crashes with a NullPointerException. So always remember: you need to use that `new` keyword to bring your object to life.
This idea of classes as blueprints and objects as the things you build is fundamental. Once you get this, you’ve unlocked a huge part of what it means to be a programmer. Keep practicing with it, and it will become second nature. You've got this.
(Outro music fades in)
You can't ask the blueprint to do something; you have to ask a specific house built from the blueprint. Code like `Book.title = "Dune";` won't work for instance variables.
Always create an object first with `new`, then use the object's variable name to access its members: `Book myBook = new Book(); myBook.title = "Dune";`.
Declaring `Dog myDog;` only creates the variable (an empty remote control holder). It doesn't point to anything yet; it's `null`. If you then try `myDog.bark();`, your program will crash with a `NullPointerException`.
Always initialize your object variables before using them: `Dog myDog = new Dog();`.
This only copies the reference (the memory address), not the object itself. Both variables now point to the same object. Changing one affects the other.
Understand that you're creating an alias or a second pointer to the original object. If you truly needed a copy, you'd have to write a special method to create a new object and copy over the attribute values one by one.
Java is strongly typed. You can't put a `Dog` object into a `Cat` variable. The line `Cat myPet = new Dog();` will cause a compiler error because the types are incompatible.
Ensure the variable type on the left matches the object type on the right (or is a superclass of the object type, which is a concept for later!). For now: `Dog myPet = new Dog();`.
We haven't covered `private` in depth yet, but you'll soon learn that attributes are often hidden to protect data. Trying to access them from outside the class will be blocked by the compiler.
Use the `public` methods (getters and setters) that the class provides to interact with its data.