(Based on your video content)
๐ Introduction
In the previous lesson, we learned how to create our first OOP-based Java program using classes and objects.
In this article, we will strengthen that understanding by working with more practical examples. We will cover:
- Creating classes (blueprints)
- Creating objects using
new - Assigning values
- Calling methods
๐ฏ Core Idea Recap
In Object-Oriented Programming:
๐ Class = Blueprint
๐ Object = Real Entity
Every object has:
- State (Data) โ Variables
- Behavior (Action) โ Methods
๐ Example 1: Student Class
๐๏ธ Step 1: Define the Class (Blueprint)
A student has:
- Name
- Age
And can perform an action:
- Study
โ Java Code:
class Student {
String name;
int age; void study() {
System.out.println(name + " is studying");
}
}
๐ Explanation
name,ageโ Object variables (data)study()โ Method (behavior)
๐ These belong to the Student class
โ๏ธ Step 2: Create Object
Student s1 = new Student();
๐ก Important
Studentโ Class names1โ Object namenewโ Creates object in memory
๐ Think of new as a factory that builds objects from blueprint
โ๏ธ Step 3: Assign Values
s1.name = "Alice";
s1.age = 22;
๐ฎ Step 4: Call Method
s1.study();
๐ฅ๏ธ Output
Alice is studying
๐ฅ Key Concept
๐ Each object has its own data
Student s2 = new Student();
s2.name = "Bob";
s2.age = 20;
Now:
s1โ Alices2โ Bob
๐ Same class, different objects, different data
๐ Example 2: Car Class
๐๏ธ Step 1: Define the Class
A car has:
- Model
- Color
And can:
- Drive
โ Java Code:
class Car {
String model;
String color; void drive() {
System.out.println(color + " " + model + " is driving");
}
}
โ๏ธ Step 2: Create Object
Car c1 = new Car();
โ๏ธ Step 3: Assign Values
c1.model = "Toyota";
c1.color = "Red";
๐ฎ Step 4: Call Method
c1.drive();
๐ฅ๏ธ Output
Red Toyota is driving
๐ Universal OOP Pattern
No matter the example, the steps are always the same:
โ Step-by-Step Flow
- Define class (blueprint)
- Create object using
new - Assign values
- Call methods
๐ Same pattern for:
- Student
- Car
- Robot
- Any real-world model
โ ๏ธ Common Beginner Mistakes
โ Mistake 1: Only Declaration
Student s1;
s1.name = "Alice"; // โ ERROR
๐ Problem:
- Object is NOT created
- Leads to NullPointerException
โ Correct Way:
Student s1 = new Student();
โ Mistake 2: Missing Brackets
s1.study; // โ WRONG
โ Correct:
s1.study(); // โ๏ธ
๐ฅ Key Takeaways
- Class = Blueprint
- Object = Real instance
new= Creates object in memory.= Access variables and methods- Each object has its own data
๐ง Final Insight
๐ OOP is not just coding
๐ It is modeling real-world concepts in code