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

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

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


Frequently Asked Questions-(FAQ)

What are classes in Java?

A class in Java is a blueprint or template used to create objects. It defines properties (variables) and behaviors (methods) that the created objects will have.

What are objects in Java?

An object is an instance of a class. It represents a real-world entity and allows programmers to access the data and methods defined inside a class.

Why do we use classes and objects in Java?

Classes and objects help organize code, improve reusability, simplify debugging, and support the core principles of object-oriented programming.

What is a constructor in Java?

A constructor is a special method that initializes an object when it is created. It has the same name as the class and does not have a return type.

What is the difference between a method and a constructor?

Methods perform actions or operations, while constructors initialize new objects. Constructors run automatically during object creation.

Why do we need constructors in Java?

Constructors ensure that an object begins its lifecycle with valid initial values. They help create fully initialized objects ready for use.

What is a default constructor?

A default constructor is automatically created by Java if no constructor is defined. It initializes object fields with default values like 0, null, or false.

What is a parameterized constructor?

Parameterized constructors accept arguments, allowing programmers to set specific values for object attributes at the time of creation.

Can a class have multiple constructors in Java?

Yes. A class can have multiple constructors using constructor overloading, where each constructor has different sets of parameters.

What is constructor overloading in Java?

Constructor overloading means creating multiple constructors with the same name but different parameters. This provides flexibility when creating objects with different initial values.

What is the 'this' keyword in Java constructors?

The this keyword refers to the current object. It is used to access instance variables and call other constructors within the same class.

How do objects store data in Java?

Objects store data in instance variables defined inside their class. Each object has its own independent copy of these variables.

Is it possible to create objects without using the new keyword?

Yes, but only in special cases like using factory methods, cloning, deserialization, or reflection. The most common way is using the new keyword.

How do classes support OOP concepts in Java?

Classes support key OOP principles like encapsulation, inheritance, abstraction, and polymorphism, making programs modular and scalable.

What is an instance variable?

An instance variable is a variable declared inside a class but outside methods. It stores data for each object individually.

No comments

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

Theme images by 5ugarless. Powered by Blogger.