DMCA.com Protection Status Java Programming Lesson 9 | Classes, Objects & Constructors — the first full OOP lesson in Java - ZAREEN TECH WAVE -Largest Tutorials Website For Freelancer ZAREEN TECH WAVE -Largest Tutorials Website For Freelancer

Header Ads

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


✅ 1️⃣ What is a Class?

A class is a blueprint for creating objects (real-world entities).

Syntax:

class ClassName { // variables (attributes) // methods (functions) }

Example:

class Car { String color; String model; void drive() { System.out.println("Car is driving"); } }

✅ 2️⃣ What is an Object?

An object is an instance of a class.

Example:

Car myCar = new Car(); // Object created myCar.color = "Red"; myCar.model = "Toyota"; myCar.drive(); // Output: Car is driving

✅ 3️⃣ Constructor

A constructor is a special method used to initialize objects.

  • Name = class name

  • No return type

Example:

class Car { String color; String model; // Constructor Car(String c, String m) { color = c; model = m; } void display() { System.out.println("Color: " + color + ", Model: " + model); } } public class Main { public static void main(String[] args) { Car myCar = new Car("Red", "Toyota"); myCar.display(); // Output: Color: Red, Model: Toyota } }

✅ 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

class Student { String name; int age; // Constructor Student(String n, int a){ name = n; age = a; } void info() { System.out.println("Name: " + name + ", Age: " + age); } } public class Main { public static void main(String[] args) { Student s1 = new Student("JITU", 21); Student s2 = new Student("ALICE", 20); s1.info(); // Name: JITU, Age: 21 s2.info(); // Name: ALICE, Age: 20 } }

✅ 6️⃣ Default Constructor vs Parameterized Constructor

class Example { Example() { // Default Constructor System.out.println("Default Constructor Called"); } Example(String msg) { // Parameterized Constructor System.out.println("Message: " + msg); } } public class Main { public static void main(String[] args) { Example obj1 = new Example(); // Default Example obj2 = new Example("Hello"); // Parameterized } }

✅ 7️⃣ This Keyword

  • Refers to the current object

  • Useful when variable names shadow parameter names

class Car { String model; Car(String model) { this.model = model; // distinguish class variable from parameter } }

✅ 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

KeywordPurpose
tryCode block to test for exceptions
catchHandle exception if occurs
finallyExecutes always (optional)
throwManually throw exception
throwsDeclare exception in method

✅ Basic Syntax

try { // risky code } catch(ExceptionType e) { // handle error } finally { // always executes }

✅ Example 1 — Divide by Zero

public class ExceptionExample { public static void main(String[] args) { int a = 10, b = 0; try { int c = a / b; System.out.println("Result: " + c); } catch (ArithmeticException e) { System.out.println("Error: Cannot divide by zero!"); } finally { System.out.println("Execution finished."); } } }

✅ Output:

Error: Cannot divide by zero! Execution finished.

✅ Example 2 — Array Index Out of Bounds

public class ArrayException { public static void main(String[] args) { int arr[] = {1,2,3}; try { System.out.println(arr[5]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Error: Invalid index!"); } finally { System.out.println("Done checking array."); } } }

✅ Multiple Catch Blocks

try { int arr[] = {1,2,3}; int x = arr[5]; int y = 10/0; } catch(ArrayIndexOutOfBoundsException e){ System.out.println("Array index problem!"); } catch(ArithmeticException e){ System.out.println("Division problem!"); } finally{ System.out.println("Always executes."); }

✅ 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:

Enter numbers: 10 0 Cannot divide by zero! Invalid array index! Execution Completed

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!


✅ NEXT PART - Lesson-10: Advanced Scanner Input & Parsing / Reading Strings & Numbers

No comments

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

Theme images by 5ugarless. Powered by Blogger.