CACS204 Object Oriented Programming in Java

Object Oriented Programming in JavaUnit 414 min read

Classes & Objects: Blueprints, Instances & OOP Core

Unit 4 of Object Oriented Programming in Java covers the foundational concepts of classes (blueprints) and objects (instances), their attributes/methods, constructors, and the four pillars of OOP (encapsulation, abstraction, inheritance, polymorphism) with Java-specific implementations.

TAKEAWAYS:

  • A class is a blueprint (template) while an object is a real instance of that blueprint, created using the new keyword.
  • Encapsulation hides data (using private fields) and exposes controlled access via getters/setters (public methods).
  • Constructors initialize objects and can be overloaded to create multiple initialization paths.
  • Java enforces abstraction by hiding implementation details (e.g., Math.sqrt() hides the algorithm).
  • Objects interact via method calls, passing data between instances (e.g., a BankAccount object calling deposit()).
  • Memory management: Objects are stored in the heap, and variables referencing them live on the stack.

1. Classes: The Blueprint

A class defines the structure (attributes) and behavior (methods) of objects. Think of it like a blueprint for a car:

  • Attributes (fields): Define what data the object holds (e.g., model, color, speed).
  • Methods: Define what actions the object can perform (e.g., accelerate(), brake()).

Syntax of a Class

public class Car {
    // Attributes (fields)
    private String model;
    private String color;
    private int speed;

    // Constructor (initializes object)
    public Car(String model, String color) {
        this.model = model;
        this.color = color;
        this.speed = 0;
    }

    // Methods
    public void accelerate(int increment) {
        speed += increment;
    }

    public void displayInfo() {
        System.out.println("Model: " + model + ", Color: " + color + ", Speed: " + speed + " km/h");
    }
}

How a Class Works: The Car Blueprint

classDiagram
    class Car {
        -String model
        -String color
        -int speed
        +Car(String, String)
        +accelerate(int)
        +displayInfo()
    }
    Car --> "1" String : model
    Car --> "1" String : color
    Car --> "1" int : speed

Real-World Analogy: BankAccount Class

  • Attributes: accountNumber, balance, customerName.
  • Methods: deposit(), withdraw(), checkBalance().
  • Example: When you open an account in Nabil Bank, the bank uses a BankAccount class to manage your data.

2. Objects: Instances of a Class

An object is a real instance of a class, created using the new keyword. Example: Two Car objects (myCar and yourCar) can be created from the same Car class.

Creating Objects

public class Main {
    public static void main(String[] args) {
        // Creating objects
        Car myCar = new Car("Toyota Corolla", "Red");
        Car yourCar = new Car("Honda Civic", "Blue");

        // Calling methods
        myCar.accelerate(50);
        myCar.displayInfo();  // Output: Model: Toyota Corolla, Color: Red, Speed: 50 km/h
    }
}

Memory Allocation of Objects

Component Location Example
Class definition Method Area Car class stored here
Object (myCar) Heap Instance of Car
Reference variable Stack myCar points to heap

Visualization: Object Creation in Memory

graph LR
    A["Stack"] -->|"myCar"| B["Heap"]
    B --> C["Car Object<br/>(model='Toyota', color='Red', speed=0)"]
    A -->|"yourCar"| D["Heap"]
    D --> E["Car Object<br/>(model='Honda', color='Blue', speed=0)"]

Real-World Example: Order Objects in Daraz

  • Class: Order (blueprint with orderId, customer, items, totalPrice).
  • Objects: Each order placed on Daraz is an instance of Order.
  • Method: processPayment() is called when you pay via Khalti.

3. Constructors: Initializing Objects

A constructor is a special method that:

  1. Has the same name as the class.
  2. Has no return type (not even void).
  3. Is called automatically when an object is created.

Default Constructor

If you don’t define any constructor, Java provides a default constructor (with no parameters).

Parameterized Constructor

public class Car {
    private String model;
    private String color;

    // Parameterized constructor
    public Car(String model, String color) {
        this.model = model;  // 'this' refers to current object
        this.color = color;
    }
}

Constructor Overloading

Java allows multiple constructors with different parameters.

public class Car {
    private String model;
    private String color;
    private int speed;

    // Constructor 1: Model and color
    public Car(String model, String color) {
        this(model, color, 0);  // Calls Constructor 2
    }

    // Constructor 2: Model, color, and speed
    public Car(String model, String color, int speed) {
        this.model = model;
        this.color = color;
        this.speed = speed;
    }
}

Real-World Example: User Class in eSewa

  • Constructor 1: User(String name, String email) (for new users).
  • Constructor 2: User(String name, String email, String phone) (for verified users).

4. The this Keyword

  • Refers to the current object.
  • Used to:
    • Distinguish between instance variables and local variables.
    • Call one constructor from another (constructor chaining).

Example: this in Action

public class Student {
    private String name;
    private int rollNo;

    public Student(String name, int rollNo) {
        this.name = name;  // 'this.name' = instance variable, 'name' = parameter
        this.rollNo = rollNo;
    }
}

Constructor Chaining with this()

public class Car {
    private String model;
    private String color;

    public Car() {
        this("Unknown", "Black");  // Calls the parameterized constructor
    }

    public Car(String model, String color) {
        this.model = model;
        this.color = color;
    }
}

5. Encapsulation: Hiding Data

  • Goal: Protect object data from unintended interference.
  • How?
    • Declare fields as private.
    • Provide public getters/setters to access/modify them.

Example: Encapsulated BankAccount

public class BankAccount {
    private String accountNumber;
    private double balance;

    // Getter for balance
    public double getBalance() {
        return balance;
    }

    // Setter for balance (with validation)
    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        }
    }
}

Why Encapsulation?

Advantage Example
Controlled access Prevents balance from being set to negative.
Flexibility in implementation Can change how balance is stored later.
Security Sensitive data (e.g., password) is hidden.

Real-World Example: Ncell’s UserProfile Class

  • Private fields: phoneNumber, simSerial, creditBalance.
  • Public methods: recharge(double amount), checkBalance().
  • Encapsulation: Prevents direct modification of creditBalance.

6. Abstraction: Hiding Complexity

  • Goal: Show only essential features and hide implementation details.
  • How?
    • Use methods to expose simplified interfaces.
    • Example: Math.sqrt() hides the algorithm.

Example: Calculator Class

public class Calculator {
    public double squareRoot(double num) {
        // Complex algorithm hidden
        return Math.sqrt(num);
    }
}

User sees:

Calculator calc = new Calculator();
double result = calc.squareRoot(25);  // Returns 5.0

User doesn’t see:

  • The actual Math.sqrt() implementation.

Real-World Example: WhatsApp’s Message Class

  • Abstraction: You send sendMessage(String text) without knowing:
    • How messages are encrypted.
    • How they’re routed via servers.
    • How delivery is confirmed.

7. Objects Interacting: Method Calls

Objects communicate by calling each other’s methods. Example: A Teacher object can assign a Student object to a Project.

Example: Student and Teacher Interaction

public class Student {
    private String name;
    public void study() {
        System.out.println(name + " is studying.");
    }
}

public class Teacher {
    public void assignProject(Student student) {
        student.study();  // Calls Student's method
    }
}

Real-World Example: Pathao’s Driver and Passenger Classes

  • Driver object: Calls acceptRide(Passenger passenger).
  • Passenger object: Calls navigateToLocation().
  • Interaction: When you book a ride, Pathao’s backend creates Driver and Passenger objects and connects them.

8. The Four Pillars of OOP (Recap)

Pillar Definition Java Example
Encapsulation Bundling data + methods; hiding internal details. private fields + public getters/setters.
Abstraction Showing only essential features. Math.sqrt() hides the algorithm.
Inheritance Reusing code via parent-child relationships. class ElectricCar extends Car
Polymorphism Same method behaves differently in different contexts. Method overriding (@Override).

In the Real World

  1. eSewa’s Transaction Class

    • Concept: Encapsulation + Abstraction
    • How? When you pay a bill via eSewa:
      • The Transaction object hides the banking API details (abstraction).
      • Your account balance is protected via getters/setters (encapsulation).
      • Example method: processPayment(double amount) validates and deducts funds.
  2. Khalti’s User and Wallet Classes

    • Concept: Objects Interaction
    • How? When you transfer money:
      • User sender = new User("Alice");
      • User receiver = new User("Bob");
      • sender.wallet.transfer(receiver.wallet, 500);
      • The Wallet class encapsulates balance and handles transactions.
  3. Daraz’s Order and Cart Classes

    • Concept: Constructor Overloading + Encapsulation
    • How? When you checkout:
      • Order order = new Order(customer, items, deliveryAddress);
      • The Order constructor validates items and sets status to "Processing".
      • Your cart items are private, and you can only modify them via addItem()/removeItem().

Worked Example: Online Shopping System

Task: Design a Product class for an online store (like Daraz).

Step 1: Define the Class

public class Product {
    private String productId;
    private String name;
    private double price;
    private int quantity;

    // Constructor
    public Product(String productId, String name, double price, int quantity) {
        this.productId = productId;
        this.name = name;
        this.price = price;
        this.quantity = quantity;
    }

    // Getters and Setters
    public String getProductId() { return productId; }
    public String getName() { return name; }
    public double getPrice() { return price; }
    public int getQuantity() { return quantity; }

    public void setPrice(double newPrice) {
        if (newPrice > 0) {
            this.price = newPrice;
        }
    }

    public void reduceQuantity(int amount) {
        if (quantity >= amount) {
            quantity -= amount;
        }
    }

    public void displayDetails() {
        System.out.println("ID: " + productId + ", Name: " + name +
                           ", Price: $" + price + ", Quantity: " + quantity);
    }
}

Step 2: Create Objects and Test

public class Main {
    public static void main(String[] args) {
        // Creating Product objects
        Product laptop = new Product("P1001", "Laptop", 999.99, 10);
        Product phone = new Product("P2002", "Smartphone", 599.99, 15);

        // Display details
        laptop.displayDetails();
        phone.displayDetails();

        // Simulate a sale
        laptop.reduceQuantity(2);
        System.out.println("After sale:");
        laptop.displayDetails();
    }
}

Output

ID: P1001, Name: Laptop, Price: $999.99, Quantity: 10
ID: P2002, Name: Smartphone, Price: $599.99, Quantity: 15
After sale:
ID: P1001, Name: Laptop, Price: $999.99, Quantity: 8

Real-World Tie-In: Daraz Inventory System

  • Objects: Each product in Daraz’s inventory is a Product object.
  • Methods:
    • reduceQuantity() is called when a customer buys an item.
    • setPrice() is used for discounts (e.g., "Buy 1 Get 1 Free").
  • Encapsulation: The actual stock database is hidden; Daraz exposes only getQuantity() and reduceQuantity().

Exam Tip

  1. Define Key Terms Precisely

    • Class: A blueprint for objects (e.g., "A Car class defines attributes like model and methods like accelerate().").
    • Object: An instance of a class (e.g., "A myCar object is created using new Car().").
    • Constructor: Initializes objects (e.g., "The Car(String, String) constructor sets model and color.").
  2. Code Structure Matters

    • Always include:
      • Class definition.
      • Private fields.
      • Public getters/setters (for encapsulation).
      • At least one constructor.
    • Example starter:
      public class X {
          private Y field1;
          private Z field2;
      
          public X(Y f1, Z f2) {
              this.field1 = f1;
              this.field2 = f2;
          }
      
          public Y getField1() { return field1; }
          // ... rest of the methods
      }
      
  3. Common Exam Questions

    • Design a class: Always include:
      • Relevant attributes (e.g., Product has price, quantity).
      • Constructors (with parameters).
      • Methods (e.g., reduceQuantity()).
    • Explain encapsulation: Mention private fields + public getters/setters.
    • Real-world analogy: Relate to apps like eSewa, Daraz, or banks.
  4. Avoid These Mistakes

    • ❌ Forgetting this when field and parameter names clash.
    • ❌ Making all fields public (breaks encapsulation).
    • ❌ Not validating input in setters (e.g., allowing negative price).
  5. Diagrams in Exams

    • If asked to draw a class diagram, use:
      classDiagram
          class Product {
              -String productId
              -String name
              -double price
              -int quantity
              +Product(String, String, double, int)
              +reduceQuantity(int)
              +displayDetails()
          }
    • Label private fields with - and public methods with +.
  6. Practical Example

    • For questions like "Design a BankAccount class", include:
      • Fields: accountNumber, balance.
      • Methods: deposit(), withdraw(), checkBalance().
      • Encapsulation: Validate withdraw(amount) to prevent overdrafts.

Final Note: Master classes vs. objects, constructors, and encapsulation—these are the core of OOP in Java and appear in every exam. Practice designing 2-3 classes (e.g., Student, BankAccount, Product) to solidify concepts.

Based on the TU BCA syllabus for Object Oriented Programming in Java (CACS204), unit 4.

Discussion

Loading…