Java Programming Lesson 9 | Classes, Objects & Constructors — the first full OOP lesson in Java
Java Programming Lesson 9
✅ We are entering Lesson-9: Classes, Objects & Constructors — the first full OOP lesson in Java. This is very important as it forms the foundation of all advanced Java programming.
📘 Lesson-9: Classes, Objects & Constructors
A class is a blueprint for creating objects (real-world entities).
Syntax:
Example:
✅ 2️⃣ What is an Object?
An object is an instance of a class.
Example:
✅ 3️⃣ Constructor
A constructor is a special method used to initialize objects.
-
Name = class name
-
No return type
Example:
✅ 4️⃣ Key Points About Objects & Classes
| Feature | Description |
|---|---|
| Class | Blueprint/Template |
| Object | Instance of Class |
| Constructor | Initializes Objects |
| Method | Defines Behavior |
| Attribute | Defines State/Property |
✅ 5️⃣ Example: Student Class
✅ 6️⃣ Default Constructor vs Parameterized Constructor
✅ 7️⃣ This Keyword
-
Refers to the current object
-
Useful when variable names shadow parameter names
✅ 8️⃣ Practice Tasks
1️⃣ Create a Book class:
-
Attributes: title, author, price
-
Constructor: initialize attributes
-
Method: display info
-
Create 2 books and display info
2️⃣ Create BankAccount class:
-
Attributes: accountNumber, balance
-
Methods: deposit(), withdraw(), displayBalance()
-
Test with 2 accounts
3️⃣ Create Rectangle class:
-
Attributes: length, width
-
Method: area(), perimeter()
-
Initialize rectangles and display results
Exception Handling (try, catch, finally)
✅ What is an Exception?
An exception is a problem that occurs during program execution.
Examples:
-
Dividing by zero
-
Accessing invalid array index
-
File not found
If not handled, program crashes.
✅ Java Exception Handling Keywords
| Keyword | Purpose |
|---|---|
try | Code block to test for exceptions |
catch | Handle exception if occurs |
finally | Executes always (optional) |
throw | Manually throw exception |
throws | Declare exception in method |
✅ Basic Syntax
✅ Example 1 — Divide by Zero
✅ Output:
✅ Example 2 — Array Index Out of Bounds
✅ Multiple Catch Blocks
✅ Why Use Exception Handling?
✔ Prevent program crash
✔ Show friendly error message
✔ Debugging easier
✔ Required in professional apps
📝 Exercise for You ✅
Create a program:
1️⃣ Take two integers from user
2️⃣ Divide them → Handle division by zero
3️⃣ Access an array element → Handle invalid index
4️⃣ Print finally message
Example Output:
Reply with:
✅ Code
✅ Output
I will check & grade it ✅🔥
🎯 Quick Quiz
1️⃣ Which block always executes?
A) try
B) catch
C) finally
2️⃣ Which exception occurs for invalid array index?
A) ArithmeticException
B) ArrayIndexOutOfBoundsException
C) NullPointerException
Reply like:
1 → ?, 2 → ?
✅ Lesson-9 Completed!


No comments
Thank You For Visit My Website.
I Will Contact As Soon As Possible.