Classes and Objects in Java
Object-Oriented Programming becomes practical when we start working with classes and objects.
These two concepts form the foundation of how Java applications are designed, from small programs to large enterprise systems.
What Is a Class?
A class is a blueprint or template. It defines what data an object will have and what actions it can perform.
A class does not represent a real object by itself. Instead, it describes how objects of that type should behave.
Think of a class as a design plan, not the actual product.
What Is an Object?
An object is a real instance created from a class. It represents something tangible that exists in memory.
While a class defines structure, an object holds actual values and performs actions.
For example, a Student class is a blueprint, but each student record created from it is an object.
Real-World Analogy
Consider a blueprint of a house. The blueprint defines rooms, doors, and windows.
The actual house built using that blueprint is the object.
In Java:
- Blueprint → Class
- Actual house → Object
Creating a Class in Java
Let’s define a simple class that represents a student.
class Student {
String name;
int age;
}
This class defines two properties: name and age.
Creating Objects from a Class
Once a class is defined, we can create objects from it.
Each object can store different values, even though they come from the same class.
public class StudentDemo {
public static void main(String[] args) {
Student s1 = new Student();
Student s2 = new Student();
s1.name = "Alice";
s1.age = 20;
s2.name = "Bob";
s2.age = 22;
System.out.println(s1.name + " - " + s1.age);
System.out.println(s2.name + " - " + s2.age);
}
}
Here, both objects are created from the same class, but each holds different data.
Why Classes and Objects Matter
Classes and objects help organize programs logically. Instead of writing scattered code, everything is grouped meaningfully.
This approach:
- Makes code easier to understand
- Improves reuse and scalability
- Matches real-world problem solving
Most professional Java applications are built entirely using classes and objects.
Objects in Real Applications
In real-world systems, objects represent:
- Users and accounts
- Orders and products
- Employees and departments
- Files and transactions
Understanding how to design classes is a critical Java skill.
What You Learned in This Lesson
- What classes and objects are
- How classes act as blueprints
- How objects store real data
- Why Java relies on classes and objects
In the next lesson, you will learn about constructors, which initialize objects properly.