Object Oriented Programming With JavaUnit 312 min read
Classes, Objects, Constructors: Definitions, Syntax, and Real-World Modeling
Unit 3 of Object Oriented Programming With Java covers the core building blocks of OOP: how to define classes as blueprints, instantiate objects, and use constructors to initialize them. You’ll learn syntax, memory allocation, and how to model real-world entities like bank accounts, student records, or eSewa transactio
TAKEAWAYS:
- A class is a blueprint for objects, combining data (fields) and behavior (methods), while an object is an instance of that class stored in memory.
- Constructors initialize objects and can be default (no-arg), parameterized, or overloaded—each must match the class name and have no return type.
- Encapsulation is enforced via
privatefields andpublicgetters/setters, ensuring controlled access to an object’s state. - The
thiskeyword distinguishes instance variables from method parameters and enables constructor chaining. - Memory allocation for objects happens in the heap, while method calls use the stack—visualizing this helps debug null pointer errors.
- Real-world systems (e.g., Daraz order queues, Ncell billing) rely on classes/objects to model entities like
Order,Customer, orTransaction.
1. Classes: The Blueprint for Objects
A class is a template that defines:
- Fields (attributes): Variables that store data (e.g.,
String name,int age). - Methods (behaviors): Functions that operate on the data (e.g.,
void display()). - Constructors: Special methods to initialize objects.
Syntax and Example
public class Student { // Class declaration
private String name; // Field (private for encapsulation)
private int rollNo; // Field
// Constructor (no return type, same name as class)
public Student(String n, int r) {
name = n;
rollNo = r;
}
// Method to display student details
public void display() {
System.out.println("Name: " + name + ", Roll No: " + rollNo);
}
}
Key Points:
- Fields are declared
privateto hide internal state (encapsulation). - Constructors are not methods—they initialize objects when created.
- Methods can access fields using the
thiskeyword (e.g.,this.name).
Visual: Class Structure
classDiagram
class Student {
-String name
-int rollNo
+Student(String, int)
+display()
}How It Works:
- Declaration:
Studentis a class with fieldsnameandrollNo. - Constructor:
Student(String n, int r)initializes these fields. - Method:
display()prints the object’s state.
2. Objects: Instances of Classes
An object is a runtime instance of a class, allocated in the heap memory. Example:
public class Main {
public static void main(String[] args) {
Student s1 = new Student("Rohan", 101); // Object creation
s1.display(); // Output: Name: Rohan, Roll No: 101
}
}
Memory Allocation:
Why This Matters:
- Objects store state (data) and behavior (methods).
- Multiple objects can exist independently (e.g.,
Student s2 = new Student("Sita", 102)).
3. Constructors: Initializing Objects
Constructors are called automatically when an object is created. Types:
- Default Constructor: No-arg, provided by Java if none is defined.
public class BankAccount { private double balance; // Default constructor (balance = 0.0) } - Parameterized Constructor: Takes arguments to set initial state.
public BankAccount(double initialBalance) { this.balance = initialBalance; } - Constructor Overloading: Multiple constructors with different parameters.
public BankAccount() { this(0.0); } // Chaining to default public BankAccount(double balance) { this.balance = balance; }
Real-World Example: eSewa Transaction
classDiagram
class User {
-String userId
-String name
+User(String, String)
}
class Transaction {
-String userId
-double amount
-String status
+Transaction(String, double)
+process()
}
User "1" --> "1..*" Transaction : "initiates"
Transaction --> "1" User : "belongs to"- Constructor: Initializes
userIdandamountwhen a payment is made. - Method:
process()updatesstatusto "Completed" or "Failed."
4. The this Keyword
- Distinguishes instance variables from parameters:
public Student(String name, int rollNo) { this.name = name; // 'this.name' refers to the field this.rollNo = rollNo; } - Constructor Chaining: Calls another constructor in the same class.
public Student() { this("Unknown", 0); // Calls parameterized constructor }
Visual: this in Action
sequenceDiagram
participant Main
participant Student
Main->>Student: new Student("Rohan", 101)
Student->>Student: this.name = "Rohan"
Student->>Student: this.rollNo = 1015. Default vs. User-Defined Constructors
| Feature | Default Constructor | User-Defined Constructor |
|---|---|---|
| Declaration | Implicit (if no constructor is defined) | Explicitly written by the programmer |
| Parameters | No arguments | Can take any number of arguments |
| Use Case | Simple objects with no initialization needs | Objects requiring specific setup |
Example: Ncell Billing System
public class Customer {
private String phoneNumber;
private double balance;
// Default constructor (balance = 0)
public Customer(String phone) {
this.phoneNumber = phone;
}
// Parameterized constructor (with initial balance)
public Customer(String phone, double balance) {
this(phone); // Chaining
this.balance = balance;
}
}
Use Case:
- A new customer signs up with just a phone number (
Customer c1 = new Customer("9800123456")). - An existing customer tops up (
Customer c2 = new Customer("9800123456", 500.0)).
6. Encapsulation: Protecting Object State
Encapsulation hides data by:
- Declaring fields as
private. - Providing
publicgetters/setters to control access.
Example: Bank Account
public class BankAccount {
private double balance;
public void deposit(double amount) {
if (amount > 0) balance += amount;
}
public void withdraw(double amount) {
if (amount <= balance) balance -= amount;
}
public double getBalance() {
return balance;
}
}
Why It’s Used in Real Systems:
- Nepal Rastra Bank (NRB): Ensures only authorized methods can modify account balances.
- Khalti: Validates transactions before updating user wallets.
7. Common Pitfalls and Best Practices
| Pitfall | Solution |
|---|---|
| Forgetting to initialize fields | Always use constructors |
Overusing public fields |
Prefer private + getters/setters |
| Not handling edge cases | Add validation in setters (e.g., if (age > 0)) |
| Memory leaks from unused objects | Use null references when done |
Exam Tip:
- Always define a constructor if you need to initialize fields. Relying on the default constructor is risky if fields are not initialized properly.
- Use
thisto avoid confusion between instance variables and parameters.
8. Worked Example: Student Management System
Task: Model a Student class with name, rollNo, and methods to set/get details. Write a program to create 2 students and display their records.
Solution:
public class Student {
private String name;
private int rollNo;
// Constructor
public Student(String name, int rollNo) {
this.name = name;
this.rollNo = rollNo;
}
// Getters
public String getName() { return name; }
public int getRollNo() { return rollNo; }
// Setters (with validation)
public void setName(String name) {
if (name != null && !name.isEmpty()) this.name = name;
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student("Rohan", 101);
Student s2 = new Student("Sita", 102);
System.out.println("Student 1: " + s1.getName() + ", " + s1.getRollNo());
System.out.println("Student 2: " + s2.getName() + ", " + s2.getRollNo());
}
}
Output:
Student 1: Rohan, 101
Student 2: Sita, 102
Visual: Object Creation Steps
9. In the Real World
eSewa App:
- Class:
Transaction - Constructor: Initializes
userId,amount, andtimestampwhen a payment is processed. - Method:
validate()checks if the user has sufficient balance before deducting funds. - Example: When you pay your electricity bill via eSewa, a
Transactionobject is created with youruserId, the bill amount, and the current time.
- Class:
Daraz Order System:
- Class:
Order - Fields:
orderId,customerId,items(a list),status("Pending", "Shipped", "Delivered"). - Constructor: Takes
customerIdand a list ofitemsto create an order. - Method:
updateStatus()changes thestatusfield when the order is shipped. - Example: When you place an order on Daraz, an
Orderobject is instantiated with yourcustomerIdand the products you selected. The system tracks its status in real-time.
- Class:
Ncell Billing:
- Class:
Customer - Fields:
phoneNumber,balance,planType("Prepaid", "Postpaid"). - Constructor: Initializes
phoneNumberand setsbalanceto 0 for new customers. - Method:
recharge(double amount)adds funds to thebalance. - Example: When you recharge your Ncell number via the app, a
Customerobject is updated with the newbalance, and the system records the transaction.
- Class:
10. Exam Tip
Constructor Questions:
- Always check if the question asks for a default or parameterized constructor.
- Example: "Create a class
Bookwithtitleandprice. Write a constructor to initialize these fields." Solution:public class Book { private String title; private double price; public Book(String title, double price) { this.title = title; this.price = price; } }
File Handling + Objects:
- Common exam question: "Write objects of a class to a file."
- Steps:
- Create the object (e.g.,
Movie m = new Movie("Inception", "Sci-Fi")). - Use
FileWriter/BufferedWriterto write fields to a file. - Example for the
Movieclass:try (BufferedWriter bw = new BufferedWriter(new FileWriter("Comedy.dat"))) { bw.write(m.getId() + "," + m.getGenre()); } catch (IOException e) { e.printStackTrace(); }
- Create the object (e.g.,
Avoid Common Mistakes:
- Not closing files: Always use
try-with-resourcesfor file operations. - Incorrect access modifiers: Fields should be
private, methodspublic. - Forgetting
this: Usethiswhen parameter names match field names.
- Not closing files: Always use
Trace Execution:
- For questions like "Explain the constructor chain", draw a diagram showing how constructors are called in inheritance.
- Example:
Final Note: Master constructors, encapsulation, and object creation—they form the backbone of OOP in Java. Practice modeling real-world entities (e.g., BankAccount, Order, Student) to solidify your understanding.
Based on the TU BITM syllabus for Object Oriented Programming With Java (IT234), unit 3.
Discussion
Loading…