IT234 Object Oriented Programming With Java

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 private fields and public getters/setters, ensuring controlled access to an object’s state.
  • The this keyword 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, or Transaction.

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 private to hide internal state (encapsulation).
  • Constructors are not methods—they initialize objects when created.
  • Methods can access fields using the this keyword (e.g., this.name).

Visual: Class Structure

classDiagram
    class Student {
        -String name
        -int rollNo
        +Student(String, int)
        +display()
    }

How It Works:

  1. Declaration: Student is a class with fields name and rollNo.
  2. Constructor: Student(String n, int r) initializes these fields.
  3. 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:

s1 referenceStack (main method)Heap (Student object)name: RohanrollNo: 101
Memory allocation for a Student object (s1 reference)

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:

  1. Default Constructor: No-arg, provided by Java if none is defined.
    public class BankAccount {
        private double balance;
        // Default constructor (balance = 0.0)
    }
    
  2. Parameterized Constructor: Takes arguments to set initial state.
    public BankAccount(double initialBalance) {
        this.balance = initialBalance;
    }
    
  3. 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 userId and amount when a payment is made.
  • Method: process() updates status to "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 = 101

5. 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:

  1. Declaring fields as private.
  2. Providing public getters/setters to control access.
Public InterfacePrivate DataGetter/Setter Methods
Encapsulation: How private data is accessed via public methods

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 this to 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

s1 = new Student("Rohan", 101)s2 = new Student("Sita", 102)Main methodHeap: Student object (Rohan)name: RohanrollNo: 101Heap: Student object (Sita)name: SitarollNo: 102
Object creation steps for two Student objects

9. In the Real World

  1. eSewa App:

    • Class: Transaction
    • Constructor: Initializes userId, amount, and timestamp when 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 Transaction object is created with your userId, the bill amount, and the current time.
  2. Daraz Order System:

    • Class: Order
    • Fields: orderId, customerId, items (a list), status ("Pending", "Shipped", "Delivered").
    • Constructor: Takes customerId and a list of items to create an order.
    • Method: updateStatus() changes the status field when the order is shipped.
    • Example: When you place an order on Daraz, an Order object is instantiated with your customerId and the products you selected. The system tracks its status in real-time.
  3. Ncell Billing:

    • Class: Customer
    • Fields: phoneNumber, balance, planType ("Prepaid", "Postpaid").
    • Constructor: Initializes phoneNumber and sets balance to 0 for new customers.
    • Method: recharge(double amount) adds funds to the balance.
    • Example: When you recharge your Ncell number via the app, a Customer object is updated with the new balance, and the system records the transaction.

10. Exam Tip

  1. Constructor Questions:

    • Always check if the question asks for a default or parameterized constructor.
    • Example: "Create a class Book with title and price. 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;
          }
      }
      
  2. File Handling + Objects:

    • Common exam question: "Write objects of a class to a file."
    • Steps:
      1. Create the object (e.g., Movie m = new Movie("Inception", "Sci-Fi")).
      2. Use FileWriter/BufferedWriter to write fields to a file.
      3. Example for the Movie class:
        try (BufferedWriter bw = new BufferedWriter(new FileWriter("Comedy.dat"))) {
            bw.write(m.getId() + "," + m.getGenre());
        } catch (IOException e) {
            e.printStackTrace();
        }
        
  3. Avoid Common Mistakes:

    • Not closing files: Always use try-with-resources for file operations.
    • Incorrect access modifiers: Fields should be private, methods public.
    • Forgetting this: Use this when parameter names match field names.
  4. Trace Execution:

    • For questions like "Explain the constructor chain", draw a diagram showing how constructors are called in inheritance.
    • Example:
Parent ConstructorChild ConstructorGrandchild Constructor
Constructor chain in inheritance (Parent → Child → Grandchild)

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…