Classes & Objects
Object-Oriented Programming (OOP) is at the heart of Java. Understanding classes and objects is essential for writing Java programs. A class is a blueprint for creating objects, while an object is an instance of a class. In this lesson, you'll learn how to define classes, create objects, work with instance variables, and understand object references.
What is a Class?
A class is a template or blueprint that defines the properties (attributes) and behaviors (methods) that objects of that class will have. Think of a class as a cookie cutter and objects as the cookies made from it.
Class vs Object Analogy
- Class: A blueprint (like a house plan)
- Object: An instance created from the blueprint (like an actual house built from the plan)
- One class can create many objects
Defining a Class
To define a class in Java, use the class keyword followed by the class name. Class names should be in PascalCase.
Click Run to execute your code
In this example:
class Student- Defines a class namedStudentString name;andint age;- Instance variables (attributes)- Each object created from this class will have its own
nameandage
Creating Objects
To create an object (instance) from a class, use the new keyword followed by the class constructor. This process is called instantiation.
Click Run to execute your code
Key points about object creation:
new Student()- Creates a new object instancestudent1andstudent2- Object references (variables that hold references to objects)- Each object has its own copy of instance variables
- You can create multiple objects from the same class
Object Reference vs Object
In Java, object variables are actually references (not the objects themselves). The variable holds the memory address where the object is stored. This is similar to how a house address points to an actual house.
Instance Variables
Instance variables are variables declared inside a class but outside any method. Each object has its own copy of these variables.
public class Car {
// Instance variables
String brand; // Each Car object has its own brand
String color; // Each Car object has its own color
int speed; // Each Car object has its own speed
// Methods can access instance variables
void displayInfo() {
System.out.println(brand + " " + color + " - Speed: " + speed);
}
}
Characteristics of instance variables:
- Each object has its own copy
- Initialized to default values (0, null, false) if not explicitly set
- Accessible from any method in the class
- Exist as long as the object exists
Object References
In Java, object variables store references (memory addresses), not the objects themselves. This means multiple variables can reference the same object.
Student student1 = new Student();
student1.name = "Alice";
student1.age = 20;
Student student2 = student1; // student2 now references the same object
System.out.println(student2.name); // Prints "Alice"
student2.name = "Bob";
System.out.println(student1.name); // Prints "Bob" (same object!)
Reference Assignment
When you assign one object reference to another, both variables point to the same object. Changes made through one reference affect the object, and those changes are visible through all references.
The null Keyword
The null keyword represents an absence of an object reference. A reference variable that is null doesn't point to any object.
Student student = null; // Reference variable doesn't point to any object
// Trying to use a null reference causes NullPointerException
// student.name = "Alice"; // ERROR: NullPointerException
// Always check for null before using
if (student != null) {
student.name = "Alice";
} else {
System.out.println("Student object is null");
}
Default Values
When you create an object with new, instance variables get default values:
int,byte,short,long:0float,double:0.0boolean:falsechar:'\u0000'- Object references:
null
Class vs Object Visualization
Understanding the relationship between classes and objects is crucial. Below is a visual representation:
The diagram shows how one class (the blueprint) can create multiple objects (instances), each with its own set of instance variables.
Common Mistakes
1. Confusing class and object
// Wrong - trying to access instance variables from class
Student.name = "Alice"; // Error! name is not static
// Correct - create an object first
Student student = new Student();
student.name = "Alice";
2. Using null references without checking
// Wrong - can cause NullPointerException
Student student = null;
System.out.println(student.name); // Runtime error!
// Correct - check for null first
Student student = null;
if (student != null) {
System.out.println(student.name);
}
3. Forgetting to use 'new' keyword
// Wrong - doesn't create an object
Student student;
student.name = "Alice"; // Error! student is null
// Correct - use 'new' to create object
Student student = new Student();
student.name = "Alice";
4. Not understanding reference assignment
// Wrong assumption - thinking this creates a copy
Student student1 = new Student();
student1.name = "Alice";
Student student2 = student1; // Both reference the same object!
student2.name = "Bob";
System.out.println(student1.name); // Prints "Bob", not "Alice"!
// Correct - create separate objects if you need copies
Student student1 = new Student();
student1.name = "Alice";
Student student2 = new Student(); // New object
student2.name = "Bob";
Exercise: Create a Book Class
Task: Create a Book class with instance variables for title, author, and pages. Then create two Book objects and display their information.
Click Run to execute your code
Show Solution
public class Book {
String title;
String author;
int pages;
void displayInfo() {
System.out.println("Title: " + title);
System.out.println("Author: " + author);
System.out.println("Pages: " + pages);
}
}
public class Exercise {
public static void main(String[] args) {
Book book1 = new Book();
book1.title = "The Java Handbook";
book1.author = "John Doe";
book1.pages = 350;
Book book2 = new Book();
book2.title = "Learning Java";
book2.author = "Jane Smith";
book2.pages = 280;
System.out.println("Book 1:");
book1.displayInfo();
System.out.println("\nBook 2:");
book2.displayInfo();
}
}
Summary
- A class is a blueprint for creating objects
- An object is an instance of a class, created with the
newkeyword - Instance variables are properties that belong to each object
- Object variables are references that point to objects in memory
- The
nullkeyword represents an absence of an object reference - Multiple references can point to the same object
- Instance variables get default values when an object is created
What's Next?
Now that you understand classes and objects, the next lesson covers Constructors, which are special methods used to initialize objects when they're created. Constructors allow you to set initial values for your objects efficiently.
Enjoying these tutorials?