📘 Introduction
In Java, Class and Object are the building blocks of Object-Oriented Programming (OOP).
- A Class is like a blueprint or template.
- An Object is a real-world entity created from a class.
👉 Think of a Class as a design of a “Car”, and an Object as an actual “Honda” or “Toyota” car built from that design.
🏗️ What is a Class?
A class defines attributes (variables) and behaviors (methods).
|
1 2 3 4 5 6 |
class ClassName { // attributes (variables) // methods (functions) } |
🚗 What is an Object?
An object is an instance of a class. It is created using the new keyword.
|
1 2 3 |
ClassName obj = new ClassName(); |
✅ Example: Student Class
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
// Defining a Class class Student { // Attributes String name; int age; // Method void displayInfo() { System.out.println("Name: " + name); System.out.println("Age: " + age); } } // Main class to run the program public class Main { public static void main(String[] args) { // Creating Objects Student s1 = new Student(); Student s2 = new Student(); // Assigning values s1.name = "John"; s1.age = 20; s2.name = "Alice"; s2.age = 22; // Calling method s1.displayInfo(); s2.displayInfo(); } } |
📊 Output
|
1 2 3 4 5 6 |
Name: John Age: 20 Name: Alice Age: 22 |
🌟 Key Points to Remember
- A class is a blueprint.
- An object is an instance of a class.
- Multiple objects can be created from one class.