Object-Oriented Programming Foundations

Classes, Objects, Fields, and Methods

ReadingPreview

You are viewing a free preview lesson.

Lesson Overview

আগের lesson-এ আমরা object-oriented design-এর মূল ধারণা শিখেছি:

  • Object state ধারণ করে
  • Object behavior expose করে
  • Class object-এর structure define করে
  • Responsibility সঠিক object-এর কাছে থাকা উচিত

এখন আমরা Java syntax ব্যবহার করে একটি simple object-oriented model তৈরি করব।

এই lesson-এর running example হবে একটি course enrollment।

একটি enrollment-এর:

  • Learner name
  • Course title
  • Completed lesson count
  • Total lesson count

থাকবে।

Enrollment নিজে:

  • একটি lesson complete করতে পারবে
  • Progress calculate করতে পারবে
  • Completion status জানাতে পারবে

এই lesson-এ direct field access ব্যবহার করা হবে, যাতে class এবং object-এর mechanics পরিষ্কার হয়।

তবে এটি temporary learning step।

পরবর্তী lessons-এ constructors এবং encapsulation ব্যবহার করে invalid state prevent করা হবে।


Learning Objectives

এই lesson শেষ করার পর আপনি পারবেন:

  • Java class declare করতে
  • Class-এর fields এবং methods identify করতে
  • new keyword দিয়ে object তৈরি করতে
  • Reference variable বুঝতে
  • Object-এর fields read এবং update করতে
  • Instance method call করতে
  • একই class থেকে multiple objects তৈরি করতে
  • Independent object state explain করতে
  • Reference assignment এবং object copying-এর difference বুঝতে
  • Default field values identify করতে
  • null reference-এর basic risk বুঝতে

Declaring a Class

Java-তে class keyword ব্যবহার করে class declare করা হয়।

public class Enrollment {

}

এখানে:

public

একটি access modifier।

class

class declaration keyword।

Enrollment

class name।

{}

class body।


Class Naming

Java class name সাধারণত PascalCase follow করে।

Correct:

Enrollment
Course
LearnerProfile
PaymentTransaction

Avoid:

enrollment
learner_profile
paymenttransaction

Class name সাধারণত একটি meaningful noun বা noun phrase হয়।


Fields Represent Object State

Class body-এর মধ্যে declared variables-কে fields বলা হয়।

public class Enrollment {

    String learnerName;
    String courseTitle;

    int completedLessons;
    int totalLessons;
}

এই fields একটি enrollment object-এর state represent করে।

Example state:

Learner: Nur
Course: Java and OOP Foundation
Completed lessons: 16
Total lessons: 20

Methods Represent Object Behavior

Class-এর মধ্যে methods object-এর behavior define করে।

public class Enrollment {

    String learnerName;
    String courseTitle;

    int completedLessons;
    int totalLessons;

    double calculateProgress() {
        return completedLessons
                * 100.0
                / totalLessons;
    }
}

এখানে:

calculateProgress()

একটি method।

Method current object-এর fields ব্যবহার করে progress calculate করে।


A Complete Initial Class

Enrollment.java

public class Enrollment {

    String learnerName;
    String courseTitle;

    int completedLessons;
    int totalLessons;

    void completeLesson() {
        if (
                completedLessons
                >= totalLessons
        ) {
            return;
        }

        completedLessons++;
    }

    double calculateProgress() {
        if (totalLessons <= 0) {
            return 0.0;
        }

        return completedLessons
                * 100.0
                / totalLessons;
    }

    boolean isCompleted() {
        return totalLessons > 0
                && completedLessons
                == totalLessons;
    }
}

এই class define করে:

State

String learnerName;
String courseTitle;
int completedLessons;
int totalLessons;

Behavior

completeLesson()
calculateProgress()
isCompleted()

Class এখনো কোনো specific enrollment নয়।

এটি enrollment objects তৈরির definition।


Creating an Object

Object তৈরি করতে new keyword ব্যবহার করা হয়।

Enrollment nurEnrollment =
        new Enrollment();

General syntax:

ClassName referenceName =
        new ClassName();

Example:

Course javaCourse =
        new Course();

Understanding the Object-Creation Statement

Enrollment nurEnrollment =
        new Enrollment();

এটি কয়েকটি অংশে ভাগ করা যায়।

Reference Type

Enrollment

Variableটি কোন type-এর object refer করতে পারবে।

Reference Variable

nurEnrollment

Object-এর reference ধরে রাখে।

Object Creation

new Enrollment()

একটি নতুন Enrollment object তৈরি করে।


Reference Variable Is Not the Object

Enrollment nurEnrollment =
        new Enrollment();

nurEnrollment object নিজে নয়।

এটি object-এর reference ধরে রাখে।

Conceptually:

nurEnrollment
      │
      └──> Enrollment object

Reference ব্যবহার করে object-এর fields এবং methods access করা হয়।


Assigning Object State

Dot operator ব্যবহার করে field access করা হয়।

nurEnrollment.learnerName =
        "Nur";

nurEnrollment.courseTitle =
        "Java and OOP Foundation";

nurEnrollment.completedLessons = 16;
nurEnrollment.totalLessons = 20;

Syntax:

objectReference.fieldName

Reading Object State

System.out.println(
        nurEnrollment.learnerName
);

Output:

Nur

আরও example:

System.out.println(
        nurEnrollment.completedLessons
);

Output:

16

Calling an Instance Method

Object reference এবং dot operator দিয়ে instance method call করা হয়।

double progress =
        nurEnrollment.calculateProgress();

Method call syntax:

objectReference.methodName()

Result:

80.0

কারণ:

16 × 100 ÷ 20 = 80

State-Changing Method

nurEnrollment.completeLesson();

Method call-এর আগে:

completedLessons = 16

Method call-এর পরে:

completedLessons = 17

Updated progress:

System.out.println(
        nurEnrollment.calculateProgress()
);

Output:

85.0

Complete Usage Example

Main.java

public class Main {

    public static void main(String[] args) {
        Enrollment nurEnrollment =
                new Enrollment();

        nurEnrollment.learnerName =
                "Nur";

        nurEnrollment.courseTitle =
                "Java and OOP Foundation";

        nurEnrollment.completedLessons = 16;
        nurEnrollment.totalLessons = 20;

        System.out.println(
                "Learner: "
                + nurEnrollment.learnerName
        );

        System.out.println(
                "Course: "
                + nurEnrollment.courseTitle
        );

        System.out.println(
                "Progress: "
                + "%.2f".formatted(
                        nurEnrollment
                                .calculateProgress()
                )
                + "%"
        );

        nurEnrollment.completeLesson();

        System.out.println(
                "Updated progress: "
                + "%.2f".formatted(
                        nurEnrollment
                                .calculateProgress()
                )
                + "%"
        );

        System.out.println(
                "Completed: "
                + nurEnrollment.isCompleted()
        );
    }
}

Output:

Learner: Nur
Course: Java and OOP Foundation
Progress: 80.00%
Updated progress: 85.00%
Completed: false

One Class, Multiple Objects

একটি class থেকে multiple objects তৈরি করা যায়।

Enrollment sakibEnrollment =
        new Enrollment();

Enrollment jalisaEnrollment =
        new Enrollment();

প্রতিটি new Enrollment() একটি separate object তৈরি করে।


Independent Object State

Enrollment sakibEnrollment =
        new Enrollment();

sakibEnrollment.learnerName =
        "Sakib";

sakibEnrollment.courseTitle =
        "Java and OOP Foundation";

sakibEnrollment.completedLessons = 18;
sakibEnrollment.totalLessons = 20;

Enrollment jalisaEnrollment =
        new Enrollment();

jalisaEnrollment.learnerName =
        "Jalisa";

jalisaEnrollment.courseTitle =
        "Java and OOP Foundation";

jalisaEnrollment.completedLessons = 20;
jalisaEnrollment.totalLessons = 20;

State:

Sakib:
18 of 20 lessons

Jalisa:
20 of 20 lessons

Method calls:

System.out.println(
        sakibEnrollment.calculateProgress()
);

System.out.println(
        jalisaEnrollment.calculateProgress()
);

Output:

90.0
100.0

একই class-এর objects হলেও তাদের state independent।


Updating One Object Does Not Update Another

sakibEnrollment.completeLesson();

এখন:

Sakib: 19 of 20
Jalisa: 20 of 20

jalisaEnrollment change হয়নি।

কারণ দুটি separate object।


Default Field Values

Object তৈরি হলে fields automatic default values পায়।

ধরা যাক:

Enrollment enrollment =
        new Enrollment();

No values assigned yet।

Field values:

Field TypeDefault Value
Reference type, such as Stringnull
int0
long0L
double0.0
booleanfalse
char'\u0000'

For the current class:

learnerName = null
courseTitle = null
completedLessons = 0
totalLessons = 0

Default Value Does Not Mean Valid State

The following object can exist:

Enrollment enrollment =
        new Enrollment();

But its state is not useful:

Learner name is missing
Course title is missing
Total lesson count is zero

Java has created a technically valid object, but the business state is incomplete।

This is an important distinction:

An object can exist in memory while still being invalid for the business domain.

Constructors will later ensure required information is provided during object creation।


Fields and Local Variables

Fields are declared in the class body।

public class Enrollment {

    int completedLessons;
}

Local variables are declared inside methods।

double calculateProgress() {
    double percentage =
            completedLessons
            * 100.0
            / totalLessons;

    return percentage;
}

Here:

completedLessons
totalLessons

are fields।

percentage

is a local variable।


Field and Local Variable Differences

FieldLocal Variable
Declared in the class bodyDeclared in a method or block
Represents object stateRepresents temporary method data
Receives a default valueMust be initialized before use
Exists as part of the objectExists during method execution

Local Variables Must Be Initialized

Invalid:

double calculateProgress() {
    double progress;

    return progress;
}

Compiler error হবে, কারণ local variable initialize করা হয়নি।

Correct:

double calculateProgress() {
    double progress =
            completedLessons
            * 100.0
            / totalLessons;

    return progress;
}

Methods Work with the Current Object

The same method behaves according to the object used to call it।

sakibEnrollment.calculateProgress();
jalisaEnrollment.calculateProgress();

The method implementation is shared by the class।

But each call reads the fields of a different current object।

Conceptually:

sakibEnrollment.calculateProgress()
→ Uses Sakib's enrollment state

jalisaEnrollment.calculateProgress()
→ Uses Jalisa's enrollment state

Reference Assignment Does Not Copy an Object

Consider:

Enrollment firstReference =
        new Enrollment();

firstReference.learnerName =
        "Subu";

Enrollment secondReference =
        firstReference;

No second object was created।

Both references point to the same object।

firstReference
       │
       ├──> Same Enrollment object
       │
secondReference

Shared Mutation Through References

secondReference.learnerName =
        "Sumu";

System.out.println(
        firstReference.learnerName
);

Output:

Sumu

Both references observe the same object state।


Creating a Separate Object

To create independent state, use new again।

Enrollment subuEnrollment =
        new Enrollment();

Enrollment sumuEnrollment =
        new Enrollment();

Now two objects exist।

subuEnrollment.learnerName =
        "Subu";

sumuEnrollment.learnerName =
        "Sumu";

Changing one object does not affect the other।


Comparing Object References

The == operator checks whether two references point to the same object।

Enrollment first =
        new Enrollment();

Enrollment second =
        new Enrollment();

System.out.println(
        first == second
);

Output:

false

Two separate objects were created।


Same Object Comparison

Enrollment first =
        new Enrollment();

Enrollment second =
        first;

System.out.println(
        first == second
);

Output:

true

Both references point to the same object।


Same Data Does Not Mean Same Object

Enrollment first =
        new Enrollment();

first.learnerName = "Nur";

Enrollment second =
        new Enrollment();

second.learnerName = "Nur";

System.out.println(
        first == second
);

Output:

false

Both objects contain the same learner name, but their identities are different।

Logical equality will be discussed in the equality lesson।


The null Reference

A reference variable can point to no object।

Enrollment enrollment = null;

Conceptually:

enrollment ──> no object

Accessing a Null Reference

Enrollment enrollment = null;

enrollment.calculateProgress();

This causes a runtime error:

NullPointerException

Because there is no actual object on which to call the method।


Basic Null Check

if (enrollment != null) {
    System.out.println(
            enrollment.calculateProgress()
    );
}

However, avoiding unnecessary null states through good construction is often better than adding null checks everywhere।


Methods Should Protect State Changes

Current method:

void completeLesson() {
    if (
            completedLessons
            >= totalLessons
    ) {
        return;
    }

    completedLessons++;
}

This method prevents:

completedLessons > totalLessons

But external code can still bypass the method:

enrollment.completedLessons = 500;

This is why direct field access is only a temporary learning step।

Later, fields will become private:

private int completedLessons;

Then callers must use controlled behavior:

enrollment.completeLesson();

Engineering Note: Domain Objects Should Not Usually Print

We could add:

void displaySummary() {
    System.out.println(
            learnerName
    );
}

This is convenient for a console tutorial।

But a reusable domain object should usually return information rather than control presentation।

Better:

double progress =
        enrollment.calculateProgress();

System.out.println(
        "%.2f%%".formatted(progress)
);

Responsibilities stay separated:

Enrollment:
Calculates progress

Main or UI layer:
Formats and displays progress

This makes the object easier to reuse in:

  • Console programs
  • Web applications
  • APIs
  • Mobile applications
  • Automated tests

Engineering Note: Classes Are Types

A class is not only a blueprint analogy।

In Java, a class also defines a type।

Enrollment enrollment;

This means:

enrollment can refer to an Enrollment object

The compiler uses the type to determine which fields and methods are available।

enrollment.calculateProgress();

is allowed because calculateProgress() is defined by Enrollment


Common Mistakes

Forgetting new

Wrong:

Enrollment enrollment =
        Enrollment();

Correct:

Enrollment enrollment =
        new Enrollment();

Declaring a Local Reference Without Initializing It

Wrong:

Enrollment enrollment;

enrollment.learnerName =
        "Nur";

The local variable does not yet hold a valid reference।

Correct:

Enrollment enrollment =
        new Enrollment();

Using a Null Reference

Wrong:

Enrollment enrollment = null;

enrollment.completeLesson();

Result:

NullPointerException

Assuming Assignment Copies the Object

Enrollment second =
        first;

This copies the reference, not the object।


Dividing Without Validation

Risky:

double calculateProgress() {
    return completedLessons
            * 100.0
            / totalLessons;
}

If totalLessons is 0, result may be invalid or misleading।

Safer:

if (totalLessons <= 0) {
    return 0.0;
}

Later, constructors will prevent zero total lessons entirely।


Treating Default Values as Meaningful Data

Enrollment enrollment =
        new Enrollment();

The default learner name null does not represent a real learner।

Required state should be explicitly initialized।


Modifying State Directly Everywhere

enrollment.completedLessons++;

This bypasses business rules।

Prefer meaningful behavior:

enrollment.completeLesson();

Practice Exercises

Exercise 1: Create a Course Class

Create a class named:

Course

Fields:

title
lessonCount
published

Method:

boolean canBePublished()

Return true when:

  • Title is not null
  • Title is not blank
  • Lesson count is greater than zero

Exercise 2: Create Two Courses

Create two independent Course objects:

Java and OOP Foundation
Backend Development with Spring Boot

Assign different lesson counts।

Confirm that updating one object does not change the other।


Exercise 3: Enrollment Progress

Create an Enrollment object for Sakib

Use:

Completed lessons: 18
Total lessons: 20

Print:

  • Progress
  • Completion status

Exercise 4: Reference Assignment

Predict and verify the output:

Enrollment first =
        new Enrollment();

first.learnerName = "Subu";

Enrollment second =
        first;

second.learnerName = "Sumu";

System.out.println(
        first.learnerName
);

Explain why the result occurs।


Exercise 5: Separate Objects

Create two independent enrollment objects।

Both can have:

Course: Java and OOP Foundation
Completed lessons: 10

Use == and explain why the result is false


Exercise 6: Protect Completion Count

Improve completeLesson() so that it does nothing when:

  • totalLessons <= 0
  • All lessons are already completed

Do not print from the method।


Predict the Output

Question 1

Enrollment enrollment =
        new Enrollment();

System.out.println(
        enrollment.completedLessons
);

Question 2

Enrollment first =
        new Enrollment();

Enrollment second =
        first;

System.out.println(
        first == second
);

Question 3

Enrollment first =
        new Enrollment();

Enrollment second =
        new Enrollment();

System.out.println(
        first == second
);

Question 4

Enrollment enrollment =
        new Enrollment();

enrollment.completedLessons = 5;
enrollment.totalLessons = 10;

enrollment.completeLesson();

System.out.println(
        enrollment.completedLessons
);

Question 5

Enrollment enrollment = null;

System.out.println(
        enrollment.calculateProgress()
);

Predict the Output Answers

Answer 1

0

int field-এর default value 0

Answer 2

true

Both references point to the same object।

Answer 3

false

Two separate objects were created।

Answer 4

6

completeLesson() state increment করেছে।

Answer 5

Runtime-এ:

NullPointerException

Knowledge Check

Question 1

Class কী define করে?

Question 2

Object কী?

Question 3

Field কী represent করে?

Question 4

Method কী represent করে?

Question 5

new keyword কী করে?

Question 6

Reference variable কী?

Question 7

একই class-এর objects কি independent state রাখতে পারে?

Question 8

Reference assignment কি নতুন object তৈরি করে?

Question 9

Object fields কি automatic default values পায়?

Question 10

Local variables কি automatic default values পায়?

Question 11

== objects-এর ক্ষেত্রে কী compare করে?

Question 12

null reference দিয়ে method call করলে কী হয়?


Knowledge Check Answers

Answer 1

একটি custom type-এর state structure এবং available behavior define করে।

Answer 2

একটি class-এর actual instance, যা real state values ধারণ করে।

Answer 3

Object-এর state বা data।

Answer 4

Object-এর behavior বা operation।

Answer 5

একটি নতুন object তৈরি করে এবং তার reference return করে।

Answer 6

একটি object-এর reference ধারণ করা variable।

Answer 7

হ্যাঁ।

Answer 8

না। এটি একই object-এর reference copy করে।

Answer 9

হ্যাঁ।

Answer 10

না। ব্যবহার করার আগে initialize করতে হয়।

Answer 11

দুটি references একই object point করছে কি না।

Answer 12

NullPointerException হতে পারে।


Lesson Summary

এই lesson-এ আমরা শিখেছি:

  • Class একটি Java type এবং object definition
  • Fields object state represent করে
  • Methods object behavior represent করে
  • new keyword নতুন object তৈরি করে
  • Reference variable object-এর reference ধরে রাখে
  • Dot operator দিয়ে fields এবং methods access করা হয়
  • একই class থেকে multiple independent objects তৈরি করা যায়
  • Methods current object-এর fields read এবং update করে
  • Fields automatic default values পায়
  • Default state business-valid নাও হতে পারে
  • Local variables automatic default values পায় না
  • Reference assignment object copy করে না
  • Multiple references একই object point করতে পারে
  • == object identity compare করে
  • null মানে reference কোনো object point করছে না
  • Null reference use করলে NullPointerException হতে পারে
  • Domain objects ideally calculation এবং rules handle করে
  • Presentation formatting সাধারণত object-এর বাইরে রাখা ভালো
  • Direct field mutation এই lesson-এর temporary teaching technique
  • Constructors এবং encapsulation দিয়ে object creation ও state changes control করা হবে

Next Lesson

পরবর্তী lesson:

Method Parameters, Return Values, and Method Design

আমরা শিখব:

  • Parameters এবং arguments
  • Return types
  • void methods
  • Multiple parameters
  • Local variables এবং method scope
  • Passing primitive values
  • Passing object references
  • Command and query methods
  • Designing small, reusable methods
  • Avoiding surprising side effects