๐Ÿงญ Topic: OOP - Encapsulation

Quick Overview :

This topic introduces Object-Oriented Programming in Java, covering the fundamental concepts of classes, objects, encapsulation, constructors, access modifiers, and method types. It establishes the foundation for building modular, maintainable, and secure Java applications.


๐Ÿ“Œ Covered in This Topic

Introduction to OOP

  • Object-Oriented Programming paradigm where programs are built using objects
  • An object combines:
    • Data (attributes / fields)
    • Behavior (methods)
  • OOP helps build large and maintainable programs
  • Benefits:
    • Better organization of code
    • Code reuse
    • Easier debugging
    • Clearer structure for large projects
    • Models real-world systems naturally

Class vs Object

  • Class:
    • A blueprint or template
    • Defines data + behavior
  • Object:
    • Instance of a class
    • Has real values in memory
    • Example: Car car1 = new Car();

Primitive vs Reference Types

  • Primitive Types: store actual value directly
    • Examples: int, double, boolean, char
    • Example: int a = 12; int b = a; a = 20; (b remains 12)
  • Reference Types: store reference (memory address) to an object
    • Examples: objects, arrays, Strings, Integer
    • Example: Car car1 = new Car(); Car car2 = car1; (both point to same object)

Wrapper Classes

  • Object versions of Javaโ€™s primitive data types
  • int โ†’ Integer, boolean โ†’ Boolean
  • Key differences (Integer vs int):
    • Memory usage (reference type vs primitive)
    • Nullability (Integer can be null)
    • Collections require objects (cannot use primitives)
    • Comparison methods (a.equals(b))
    • Provided utility methods
  • Example: List<Integer> nums = new ArrayList<>();

Object Comparison

  • a == b expression:
    • Compares references (memory addresses)
    • Checks if two variables point to the same object
    • Example: list1 == list2 โ†’ false (different objects)
  • equals() method:
    • Compares object values (content)
    • Works if the class overrides equals()
    • Example: list1.equals(list2) โ†’ true (same content)

Access Modifiers

  • public: accessible from anywhere
  • private: accessible only inside the same class
  • protected: accessible in the same package and subclasses
  • package-private (default): no keyword; accessible within the same package
class Car {
    public int speed;
    private int fuel;
    protected String model;
    int year;  // package-private
}

Constructors

  • A special method used to initialize objects
  • Rules:
    1. Constructor name equals the class name
    2. No return type - never returns anything
    3. Usually initializes fields
    4. All classes need at least one constructor
  • Default constructor (if none provided): CLASSNAME(){ }

Overloaded Constructors

  • Multiple constructors with different parameter lists
  • Offer different valid ways to initialize an object
  • Provide flexibility for object creation
  • No duplicate initialization logic
  • All constructors enforce class rules

Instance vs Static

  • Instance Methods:
    • Belong to an object
    • Require an instance to call
    • Can access all fields
  • Static Methods:
    • Belong to the class itself
    • Called without creating an object
    • Cannot access instance fields directly
  • Static Fields:
    • Shared across all instances of the class
    • Store class-level data

Method Overloading

  • Multiple methods with same name but different parameter lists
  • Allowed for both static and instance methods
int add(int a, int b) { return a + b; }
int add(int a, int b, int c) { return a + b + c; }

Encapsulation

  • Bundling data and methods in a class
  • Hides data, promotes modularity
  • Ensures โ€œsensitiveโ€ data inside a class is protected from direct access
  • Implementation:
    1. Declare class variables/attributes as private
    2. Provide public getter and setter methods
public class Person {
    private int age;
    public int getAge() { return age; }
    public void setAge(int value) {
        if (value >= 0) { age = value; }
    }
}

Why Encapsulation?

  • Better control of class attributes and methods
  • Class attributes can be made read-only (only getter) or write-only (only setter)
  • Flexible: programmer can change one part of code without affecting other parts
  • Increased security of data

Mutability vs Immutability

  • Mutable objects: fields can change after creation
  • Immutable objects: state cannot change once created
  • Why immutability matters:
    • Safer when sharing between threads
    • Easier to reason about
    • Reduces unexpected side effects
public final class Student {
    private final String name;
    private final int id;
    public Student(String name, int id) {
        this.name = name;
        this.id = id;
    }
    // Only getters, no setters
}

The Four Pillars of OOP

  1. Encapsulation: Bundling data and methods in a class. Hides data, promotes modularity.
  2. Inheritance: Classes inherit properties and behaviors. Enables code reuse and hierarchy.
  3. Polymorphism: Treating different class objects as a common superclass. Enhances flexibility and modularity.
  4. Abstraction: Focusing on essential characteristics, ignoring unnecessary details. Improves code maintainability and readability.

๐Ÿ“‘ Slides & Materials


๐Ÿ› ๏ธ Workshop & Assignments

๐Ÿ’ฌ Workshop: Course Registration System

  • ๐Ÿ“‚ WS-02-intro-to-oop Repository
  • Build a course registration system using OOP concepts
  • Complete TODO sections in:
    • Student Class: addCourse(), dropCourse(), showRegisteredCourses()
    • RegistrationSystem Class: addCourseToSystem(), findCourseByCode(), showAllCourses()
    • Main Class: Create courses, register student, drop courses, print results
  • Constraints: Use ArrayList<Course>, no public fields, donโ€™t modify Course class
  • Bonus: Prevent duplicate registration, limit courses per student, search by name

๐Ÿงฎ Assignment: OOP & API

  • ๐Ÿ“‚ HW-03-oop-and-api Repository
  • Part 1: Rational Class - Implement rational number operations
    • Complete Rational.java (addition, subtraction, multiplication, division)
    • Both instance and static methods
  • Part 2: Movie Explorer - Build API-driven movie browser
    • Design Movie class from JSON structure
    • Parse JSON responses using Gson (Jackson also included)
    • Implement console menu for genre selection and movie browsing
    • Bonus: Fetch and display detailed movie information by ID
  • APIs: https://api.meshcomp.ir/api/v1/
  • Deadline: May 1st (11 Ordibehesht)

RepositoryDescription
๐Ÿ“‚ WS-02-intro-to-oopWorkshop: Course Registration System - Implement OOP concepts with TODO sections
๐Ÿ“‚ HW-03-oop-and-apiAssignment: Rational Calculator + Movie Explorer with API integration

๐ŸŒ Additional Resources


โฉ Navigation


Tip :

Encapsulation is the foundation of good OOP design. Always start with private fields and only expose whatโ€™s necessary through getters and setters. This protects your data and makes your code more maintainable. Also, when working with JSON APIs, inspect the raw response first to understand the data structure before designing your classes!