Object-Oriented Programming Foundations

Constructors and Valid Object Creation

ReadingPreview

You are viewing a free preview lesson.

Lesson Overview

এখন পর্যন্ত আমরা object তৈরি করেছি এভাবে:

Enrollment enrollment =
        new Enrollment();

enrollment.learnerName = "Nur";
enrollment.courseTitle =
        "Java and OOP Foundation";

enrollment.completedLessons = 0;
enrollment.totalLessons = 20;

এই approach শেখার জন্য simple, কিন্তু design হিসেবে দুর্বল।

Object তৈরি হওয়ার পর কিছু সময়ের জন্য তার state এমন থাকতে পারে:

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

তারপর caller ধাপে ধাপে fields assign করে।

সমস্যা হলো caller:

  • একটি required field ভুলে যেতে পারে
  • Invalid value দিতে পারে
  • Object সম্পূর্ণ initialize হওয়ার আগেই method call করতে পারে
  • Different জায়গায় different initialization rules অনুসরণ করতে পারে

Constructor object creation-এর সময় required state গ্রহণ করে এবং object-কে শুরু থেকেই meaningful state-এ তৈরি করতে সাহায্য করে।

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

  • Constructor কী
  • Constructor কখন execute হয়
  • Default constructor
  • No-argument constructor
  • Parameterized constructor
  • Required state
  • Constructor validation
  • Partially initialized object prevent করা
  • Constructor এবং method-এর পার্থক্য
  • Valid object creation-এর practical design principles

Learning Objectives

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

  • Java constructor declare করতে
  • new expression-এর সঙ্গে constructor call explain করতে
  • Compiler-provided default constructor বুঝতে
  • Parameterized constructor ব্যবহার করতে
  • Required fields object creation-এর সময় initialize করতে
  • Invalid constructor arguments reject করতে
  • Partially initialized object-এর সমস্যা explain করতে
  • Constructor এবং normal method আলাদা করতে
  • Constructor-এর responsibility সীমিত রাখতে
  • Object-কে valid initial state-এ তৈরি করতে

What Is a Constructor?

Constructor হলো একটি special class member, যা নতুন object তৈরি হওয়ার সময় execute হয়।

Example:

public class Enrollment {

    String learnerName;
    String courseTitle;
    int totalLessons;

    Enrollment(
            String initialLearnerName,
            String initialCourseTitle,
            int initialTotalLessons
    ) {
        learnerName =
                initialLearnerName;

        courseTitle =
                initialCourseTitle;

        totalLessons =
                initialTotalLessons;
    }
}

Object creation:

Enrollment enrollment =
        new Enrollment(
                "Nur",
                "Java and OOP Foundation",
                20
        );

new Enrollment(...) একটি object তৈরি করে এবং matching constructor execute করে।


Constructor Syntax

Constructor-এর syntax:

ClassName(
        parameters
) {
    // Initialization logic
}

Example:

Enrollment(
        String initialLearnerName,
        String initialCourseTitle,
        int initialTotalLessons
) {
}

Constructor-এর:

  • Name class name-এর সঙ্গে same
  • কোনো return type নেই
  • void-ও লেখা হয় না
  • Object creation-এর সময় call হয়

Constructor Has No Return Type

Wrong:

void Enrollment(
        String learnerName
) {
}

এটি constructor নয়।

এটি Enrollment নামের একটি normal method, কারণ void return type আছে।

Correct constructor:

Enrollment(
        String learnerName
) {
}

Constructor-এর আগে কোনো return type লেখা হয় না।


Constructor Runs During Object Creation

Enrollment enrollment =
        new Enrollment(
                "Nur",
                "Java and OOP Foundation",
                20
        );

Conceptually:

1. নতুন Enrollment object-এর জন্য memory allocate হয়
2. Fields default values পায়
3. Constructor execute হয়
4. Constructor fields initialize করে
5. Object reference caller-এর কাছে ফিরে আসে

Caller constructor body direct call করে না।

Wrong:

enrollment.Enrollment();

Constructor শুধু object creation-এর অংশ হিসেবে call হয়।


The Problem with Two-Step Initialization

Without a parameterized constructor:

Enrollment enrollment =
        new Enrollment();

enrollment.learnerName = "Nur";
enrollment.courseTitle =
        "Java and OOP Foundation";

enrollment.totalLessons = 20;

এই code-এ object প্রথমে incomplete state-এ তৈরি হয়।

learnerName = null
courseTitle = null
totalLessons = 0

তারপর caller object complete করে।

কিন্তু caller যদি একটি field assign করতে ভুলে যায়:

Enrollment enrollment =
        new Enrollment();

enrollment.learnerName = "Nur";
enrollment.totalLessons = 20;

courseTitle থেকে যাবে:

null

Object technically exists, কিন্তু business perspective-এ incomplete।


Required State in the Constructor

যে information ছাড়া object meaningful নয়, সেটি constructor-এ required করা যায়।

Enrollment(
        String initialLearnerName,
        String initialCourseTitle,
        int initialTotalLessons
) {
    learnerName =
            initialLearnerName;

    courseTitle =
            initialCourseTitle;

    totalLessons =
            initialTotalLessons;
}

এখন object তৈরি করতে caller-কে তিনটি value দিতেই হবে।

Enrollment enrollment =
        new Enrollment(
                "Nur",
                "Java and OOP Foundation",
                20
        );

Missing argument:

Enrollment enrollment =
        new Enrollment(
                "Nur",
                "Java and OOP Foundation"
        );

Compile হবে না।

Required state compiler-visible object creation contract-এর অংশ হয়েছে।


Compiler-Provided Default Constructor

যদি class-এ কোনো constructor declare না করা হয়, Java compiler একটি no-argument constructor provide করে।

Example:

public class Course {

    String title;
}

তখন এটি valid:

Course course =
        new Course();

Compiler conceptually এমন একটি constructor provide করে:

Course() {
}

এটিকে commonly default constructor বলা হয়।


Default Constructor Is Conditional

যদি আপনি নিজে কোনো constructor declare করেন, compiler আর automatic no-argument constructor provide করে না।

public class Course {

    String title;

    Course(
            String initialTitle
    ) {
        title =
                initialTitle;
    }
}

এখন:

Course course =
        new Course();

compile হবে না।

Valid:

Course course =
        new Course(
                "Java and OOP Foundation"
        );

Important rule:

Compiler no-argument constructor শুধু তখনই দেয়, যখন class-এ কোনো constructor declare করা হয়নি।


Explicit No-Argument Constructor

প্রয়োজনে নিজে no-argument constructor declare করা যায়।

public class Course {

    String title;

    Course() {
        title =
                "Untitled Course";
    }
}

Usage:

Course course =
        new Course();

Initial state:

title = Untitled Course

কিন্তু no-argument constructor ব্যবহার করা উচিত কি না, তা domain-এর ওপর নির্ভর করে।

যদি title ছাড়া course meaningful না হয়, তাহলে no-argument constructor object-কে weak initial state-এ তৈরি করতে পারে।


Parameterized Constructor

যে constructor parameters গ্রহণ করে, তাকে parameterized constructor বলা হয়।

Course(
        String initialTitle,
        int initialLessonCount
) {
    title =
            initialTitle;

    lessonCount =
            initialLessonCount;
}

Usage:

Course javaCourse =
        new Course(
                "Java and OOP Foundation",
                20
        );

Constructor arguments object-এর initial state নির্ধারণ করে।


Constructor Validation

Constructor শুধু values assign করবে না।

এটি invalid object creation reject করতে পারে।

Enrollment(
        String initialLearnerName,
        String initialCourseTitle,
        int initialTotalLessons
) {
    if (
            initialLearnerName == null
            || initialLearnerName.isBlank()
    ) {
        throw new IllegalArgumentException(
                "Learner name is required."
        );
    }

    if (
            initialCourseTitle == null
            || initialCourseTitle.isBlank()
    ) {
        throw new IllegalArgumentException(
                "Course title is required."
        );
    }

    if (initialTotalLessons <= 0) {
        throw new IllegalArgumentException(
                "Total lessons must be greater than zero."
        );
    }

    learnerName =
            initialLearnerName.strip();

    courseTitle =
            initialCourseTitle.strip();

    totalLessons =
            initialTotalLessons;
}

Invalid input হলে constructor object creation complete হতে দেবে না।


Why Throw an Exception?

ধরা যাক caller লিখেছে:

Enrollment enrollment =
        new Enrollment(
                "",
                "Java and OOP Foundation",
                20
        );

Blank learner name নিয়ে object তৈরি করা meaningful নয়।

Constructor যদি শুধু silently return করত:

if (
        initialLearnerName == null
        || initialLearnerName.isBlank()
) {
    return;
}

তাহলে object তৈরি হয়ে যেত, কিন্তু incomplete state-এ।

Constructor থেকে normal method-এর মতো creation cancel করার জন্য শুধু return যথেষ্ট নয়।

Exception invalid object creation stop করে।

throw new IllegalArgumentException(
        "Learner name is required."
);

Exception handling পরবর্তী course content-এ বিস্তারিত শেখানো হবে।

এখানে গুরুত্বপূর্ণ ধারণা:

Invalid constructor arguments হলে invalid object তৈরি করার চেয়ে creation fail করা ভালো।


Assign Only After Validation

Weak ordering:

learnerName =
        initialLearnerName;

if (
        learnerName == null
        || learnerName.isBlank()
) {
    throw new IllegalArgumentException(
            "Learner name is required."
    );
}

Object creation শেষ হবে না, তাই final object caller পাবে না।

তবুও clearer pattern হলো:

Validate inputs
Normalize inputs
Assign fields

Example:

if (
        initialLearnerName == null
        || initialLearnerName.isBlank()
) {
    throw new IllegalArgumentException(
            "Learner name is required."
    );
}

String normalizedLearnerName =
        initialLearnerName.strip();

learnerName =
        normalizedLearnerName;

Validation এবং assignment-এর order constructor logic বুঝতে সহজ করে।


Normalizing Constructor Input

Validation-এর পাশাপাশি constructor input normalize করতে পারে।

learnerName =
        initialLearnerName.strip();

courseTitle =
        initialCourseTitle.strip();

Caller যদি দেয়:

"  Nur  "

Stored value হবে:

"Nur"

Normalization consistent state তৈরি করতে সাহায্য করে।

তবে constructor unexpectedভাবে data transform করা উচিত নয়।

Example:

learnerName =
        initialLearnerName
                .strip()
                .toUpperCase();

সব names uppercase করা domain requirement না হলে surprising হতে পারে।


Initial State Should Be Complete

একটি নতুন enrollment-এর sensible initial state:

Learner name: Nur
Course title: Java and OOP Foundation
Completed lessons: 0
Total lessons: 20

completedLessons constructor parameter না হলেও চলে, কারণ নতুন enrollment naturally zero progress দিয়ে শুরু হতে পারে।

Enrollment(
        String initialLearnerName,
        String initialCourseTitle,
        int initialTotalLessons
) {
    // Validation

    learnerName =
            initialLearnerName.strip();

    courseTitle =
            initialCourseTitle.strip();

    completedLessons = 0;

    totalLessons =
            initialTotalLessons;
}

completedLessons = 0 automatic default-এর same।

Explicit assignment এখানে business intent clear করতে পারে:

A new enrollment starts with zero completed lessons.

Required State vs Optional State

সব fields constructor parameter হওয়া দরকার নেই।

Ask:

Object meaningfulভাবে exist করতে কোন values অবশ্যই প্রয়োজন?

Enrollment-এর জন্য required হতে পারে:

Learner
Course
Total lessons

Initial completed count naturally হতে পারে:

0

Optional বা later-changing state হতে পারে:

Cancellation reason
Completion timestamp
Certificate ID

সব fields constructor-এ দিলে constructor unnecessarily large হতে পারে।


Constructor Should Establish Invariants

Object invariant হলো এমন rule, যা valid object-এর জন্য সবসময় true থাকা উচিত।

Enrollment invariants:

Learner name must not be blank
Course title must not be blank
Total lessons must be greater than zero
Completed lessons must not be negative
Completed lessons must not exceed total lessons

Constructor initial invariants establish করে।

Methods future state changes-এর সময় invariants preserve করে।

boolean completeLessons(
        int lessonCount
) {
    if (lessonCount <= 0) {
        return false;
    }

    int updatedCount =
            completedLessons
            + lessonCount;

    if (
            updatedCount
            > totalLessons
    ) {
        return false;
    }

    completedLessons =
            updatedCount;

    return true;
}

Constructor valid beginning নিশ্চিত করে।

Method valid transitions নিশ্চিত করে।


Complete Enrollment Class

Enrollment.java

public class Enrollment {

    String learnerName;
    String courseTitle;

    int completedLessons;
    int totalLessons;

    Enrollment(
            String initialLearnerName,
            String initialCourseTitle,
            int initialTotalLessons
    ) {
        if (
                initialLearnerName == null
                || initialLearnerName.isBlank()
        ) {
            throw new IllegalArgumentException(
                    "Learner name is required."
            );
        }

        if (
                initialCourseTitle == null
                || initialCourseTitle.isBlank()
        ) {
            throw new IllegalArgumentException(
                    "Course title is required."
            );
        }

        if (initialTotalLessons <= 0) {
            throw new IllegalArgumentException(
                    "Total lessons must be greater than zero."
            );
        }

        learnerName =
                initialLearnerName.strip();

        courseTitle =
                initialCourseTitle.strip();

        completedLessons = 0;

        totalLessons =
                initialTotalLessons;
    }

    boolean completeLessons(
            int lessonCount
    ) {
        if (lessonCount <= 0) {
            return false;
        }

        int updatedCount =
                completedLessons
                + lessonCount;

        if (
                updatedCount
                > totalLessons
        ) {
            return false;
        }

        completedLessons =
                updatedCount;

        return true;
    }

    int calculateRemainingLessons() {
        return totalLessons
                - completedLessons;
    }

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

    boolean isCompleted() {
        return completedLessons
                == totalLessons;
    }
}

Using the Constructor

Main.java

public class Main {

    public static void main(String[] args) {
        Enrollment nurEnrollment =
                new Enrollment(
                        "Nur",
                        "Java and OOP Foundation",
                        20
                );

        nurEnrollment.completeLessons(
                4
        );

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

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

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

        System.out.println(
                "Remaining lessons: "
                + nurEnrollment
                        .calculateRemainingLessons()
        );

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

Output:

Learner: Nur
Course: Java and OOP Foundation
Progress: 20.00%
Remaining lessons: 16
Completed: false

Invalid Object Creation

Enrollment invalidEnrollment =
        new Enrollment(
                "Nur",
                "Java and OOP Foundation",
                0
        );

Result:

IllegalArgumentException:
Total lessons must be greater than zero.

Variable assignment complete হবে না।

invalidEnrollment

কোনো successfully created object reference পাবে না।


Constructor vs Method

ConstructorMethod
Object initialization-এর জন্যObject behavior-এর জন্য
Name class name-এর sameMeaningful action বা query name
Return type নেইReturn type required
new-এর সময় call হয়Object reference দিয়ে call হয়
Initial valid state establish করেExisting state read বা change করে

Constructor:

Enrollment(
        String learnerName,
        String courseTitle,
        int totalLessons
) {
}

Method:

boolean completeLessons(
        int lessonCount
) {
}

Constructor Is Not a General Setup Method

Weak design:

Enrollment() {
}

void initialize(
        String learnerName,
        String courseTitle,
        int totalLessons
) {
}

Usage:

Enrollment enrollment =
        new Enrollment();

enrollment.initialize(
        "Nur",
        "Java and OOP Foundation",
        20
);

এটি আবার two-step initialization তৈরি করেছে।

Caller initialize() call করতে ভুলে যেতে পারে।

Required state constructor-এ নেওয়া stronger design।


Avoid Calling Overridable Behavior from Constructors

Beginner level-এ একটি useful rule:

Constructor simple রাখুন এবং object-এর own state initialize করুন।

Constructor-এর মধ্যে complex behavior, external calls বা subclass-dependent methods call করা risk তৈরি করতে পারে।

Avoid:

Enrollment(
        String learnerName
) {
    sendWelcomeEmail();
    saveToDatabase();
    publishEvent();
}

Object construction এবং external side effects আলাদা রাখা ভালো।

A constructor should generally not:

  • Call databases
  • Call remote APIs
  • Send emails
  • Start threads
  • Perform expensive workflows
  • Depend on partially initialized subclass behavior

Constructor Should Not Do Too Much

Good constructor responsibilities:

  • Required input গ্রহণ করা
  • Input validate করা
  • Simple normalization করা
  • Fields initialize করা
  • Initial invariants establish করা

Poor constructor responsibilities:

  • Database queries
  • File loading
  • Network requests
  • Payment processing
  • Email sending
  • Large business workflow execution

Heavy work object creation unpredictable এবং difficult to test করে।


Engineering Note: Constructors Protect Only Creation

Constructor object-কে valid state-এ তৈরি করে।

কিন্তু fields direct accessible থাকলে caller পরে invariant ভাঙতে পারে।

Enrollment enrollment =
        new Enrollment(
                "Nur",
                "Java and OOP Foundation",
                20
        );

enrollment.totalLessons = -5;

Constructor ভালো হলেও object আর valid নয়।

এই কারণেই constructors এবং encapsulation একসঙ্গে কাজ করে।

Constructor:
Creates valid state

Encapsulation:
Protects valid state after creation

পরবর্তী lessons-এ fields private করা হবে।


Design Trade-Off: Constructor Validation vs Boundary Validation

ধরা যাক user form থেকে course title এসেছে।

Application boundary-তে validation হতে পারে:

Course title is required
Maximum length is 150 characters

Constructor-এও core invariant validate করা যেতে পারে:

Title must not be blank

দুই জায়গার validation duplicate মনে হতে পারে, কিন্তু responsibilities আলাদা।

Boundary validation:

  • User-friendly error তৈরি করে
  • Input format check করে
  • Multiple errors collect করতে পারে

Constructor validation:

  • Invalid domain object creation prevent করে
  • Internal callers-এর ভুল থেকেও object protect করে

Core invariant শুধু UI validation-এর ওপর নির্ভর করা উচিত নয়।


Constructor Parameter Count

Constructor-এ অনেক parameters থাকলে object design review করা উচিত।

Example:

Enrollment(
        String learnerName,
        String learnerEmail,
        String courseTitle,
        long coursePrice,
        int totalLessons,
        int completedLessons,
        boolean active,
        String status,
        String paymentReference
) {
}

Possible problems:

  • Multiple objects-এর data এক class-এ ঢুকছে
  • Object too many responsibilities নিচ্ছে
  • Argument order error-prone
  • Related concepts আলাদা করা হয়নি

Future composition design:

Enrollment(
        Learner learner,
        Course course
) {
}

Constructor ছোট করার জন্য blindly parameters remove করবেন না।

প্রথমে domain relationships improve করুন।


Multiple Constructors

একটি class-এর multiple constructors থাকতে পারে, যদি তাদের parameter lists different হয়।

Conceptual example:

Enrollment(
        String learnerName,
        String courseTitle,
        int totalLessons
) {
}

Enrollment(
        String learnerName,
        String courseTitle,
        int completedLessons,
        int totalLessons
) {
}

এটিকে constructor overloading বলা হয়।

কিন্তু multiple constructors valid use cases represent করা উচিত।

Unnecessary overloads object creation rules confusing করতে পারে।

Constructor overloading এবং this() পরবর্তী lesson-এ বিস্তারিত শেখানো হবে।


Common Mistakes

Writing a Return Type

Wrong:

void Enrollment() {
}

এটি constructor নয়।

Correct:

Enrollment() {
}

Using the Wrong Constructor Arguments

Given:

Enrollment(
        String learnerName,
        String courseTitle,
        int totalLessons
) {
}

Wrong:

new Enrollment(
        "Nur",
        20,
        "Java Foundation"
);

Argument types এবং order match করতে হবে।


Expecting Automatic No-Argument Constructor

Once this exists:

Enrollment(
        String learnerName
) {
}

This may no longer compile:

new Enrollment();

নিজে no-argument constructor declare না করলে compiler এটি provide করবে না।


Leaving Required State Outside the Constructor

Weak:

Enrollment enrollment =
        new Enrollment();

enrollment.learnerName = "Nur";

Object incomplete অবস্থায় exist করতে পারে।


Accepting Invalid Values

Enrollment(
        int totalLessons
) {
    this.totalLessons =
            totalLessons;
}

Without validation:

new Enrollment(-10);

possible হয়ে যায়।


Doing External Work in a Constructor

Enrollment() {
    sendEmail();
    saveToDatabase();
}

Construction expensive, unpredictable এবং hard to test হয়।


Making Every Field a Constructor Parameter

সব fields required initial state নয়।

Derived, optional, বা later-changing values constructor overload করতে পারে।


Practice Exercises

Exercise 1: Course Constructor

Create a Course class with:

title
totalLessons
priceInPaisa

Constructor rules:

  • Title required
  • Total lessons greater than zero
  • Price cannot be negative
  • Store stripped title

Exercise 2: Default Constructor Behavior

Create a class without any constructor।

Confirm:

new ClassName();

works।

Then add a parameterized constructor and observe whether the no-argument call still compiles।

Explain why।


Exercise 3: Valid Enrollment Creation

Create:

new Enrollment(
        "Jalisa",
        "Java and OOP Foundation",
        20
);

Print its initial progress।

Expected:

0.0

Exercise 4: Invalid Enrollment Creation

Try:

new Enrollment(
        "Subu",
        "",
        20
);

Identify which validation fails।


Exercise 5: Required vs Optional State

For a Learner object, classify these fields:

name
email
profilePhotoUrl
emailVerified
createdAt
lastLoginAt

Which values should be required during construction?

Which values can receive meaningful defaults or be assigned later?

Explain your reasoning।


Exercise 6: Constructor Responsibility

Review:

Course(
        String title
) {
    validateTitle(title);
    saveToDatabase();
    sendNotification();
}

Identify which operations belong in construction and which should move elsewhere।


Exercise 7: Invariants

Write at least four invariants for a Course object।

Then decide which invariants should be established in the constructor।


Predict the Result

Question 1

public class Course {

    String title;
}
Course course =
        new Course();

Will it compile?


Question 2

public class Course {

    String title;

    Course(
            String initialTitle
    ) {
        title =
                initialTitle;
    }
}
Course course =
        new Course();

Will it compile?


Question 3

Enrollment enrollment =
        new Enrollment(
                "Nur",
                "Java Foundation",
                20
        );

System.out.println(
        enrollment.completedLessons
);

Assume the constructor sets initial completed lessons to 0


Question 4

new Enrollment(
        "Nur",
        "Java Foundation",
        -5
);

What happens when the constructor validates total lessons?


Predict the Result Answers

Answer 1

হ্যাঁ।

Class-এ কোনো constructor declare করা হয়নি, তাই compiler একটি no-argument constructor provide করবে।

Answer 2

না।

Parameterized constructor declare করার পরে compiler automatic no-argument constructor provide করবে না।

Answer 3

0

A new enrollment starts with zero completed lessons।

Answer 4

Constructor IllegalArgumentException throw করবে এবং object creation সফল হবে না।


Knowledge Check

Question 1

Constructor কী?

Question 2

Constructor-এর name কী হতে হয়?

Question 3

Constructor-এর return type কী?

Question 4

Constructor কখন execute হয়?

Question 5

Compiler কখন default no-argument constructor provide করে?

Question 6

Parameterized constructor কী?

Question 7

Required state constructor-এ নেওয়া useful কেন?

Question 8

Constructor validation-এর purpose কী?

Question 9

Constructor থেকে শুধু return করে invalid object creation stop করা যায় কি?

Question 10

Constructor এবং method-এর main difference কী?

Question 11

Constructor external API call বা database operation না করাই ভালো কেন?

Question 12

Constructor valid state তৈরি করলেও encapsulation কেন প্রয়োজন?


Knowledge Check Answers

Answer 1

Object creation-এর সময় execute হওয়া special class member, যা initial state establish করে।

Answer 2

Class name-এর same।

Answer 3

Constructor-এর কোনো return type নেই; void-ও নয়।

Answer 4

new expression দিয়ে object তৈরি হওয়ার সময়।

Answer 5

যখন class-এ কোনো constructor explicitly declare করা হয়নি।

Answer 6

যে constructor parameters গ্রহণ করে।

Answer 7

Object incomplete state-এ তৈরি হওয়া prevent করে এবং creation contract clear করে।

Answer 8

Invalid arguments reject করে object-কে শুরু থেকেই valid state-এ তৈরি করা।

Answer 9

না। শুধু return করলে constructor শেষ হবে এবং object তৈরি হয়ে যেতে পারে। Invalid creation stop করতে exception ব্যবহার করা যায়।

Answer 10

Constructor object initialize করে এবং new-এর সময় call হয়। Method existing object-এর behavior perform করে এবং explicit method call-এর মাধ্যমে execute হয়।

Answer 11

Object creation expensive, unpredictable, side-effect-heavy এবং difficult to test হয়ে যায়।

Answer 12

Directly accessible fields পরে invalid value দিয়ে পরিবর্তন করা যেতে পারে। Encapsulation post-construction state changes control করে।


Lesson Summary

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

  • Constructor object creation-এর সময় execute হয়
  • Constructor-এর name class name-এর same
  • Constructor-এর কোনো return type নেই
  • new expression matching constructor call করে
  • Compiler শুধু constructor না থাকলে default no-argument constructor দেয়
  • Parameterized constructor required input গ্রহণ করে
  • Constructor two-step initialization prevent করতে পারে
  • Required state object creation contract-এর অংশ হওয়া উচিত
  • Constructor invalid arguments reject করতে পারে
  • IllegalArgumentException invalid object creation stop করতে পারে
  • Validation-এর পরে fields assign করা clearer
  • Constructor simple normalization করতে পারে
  • New object-এর meaningful initial defaults থাকতে পারে
  • সব fields constructor parameters হওয়া দরকার নেই
  • Constructor initial invariants establish করে
  • Methods future state transitions-এর invariants protect করে
  • Constructor এবং method আলাদা concepts
  • Constructor external workflows চালানোর জায়গা নয়
  • Too many constructor parameters design problem indicate করতে পারে
  • Constructor valid state তৈরি করে
  • Encapsulation object creation-এর পর সেই valid state protect করে

Next Lesson

পরবর্তী lesson:

The this Keyword and Method Overloading

আমরা শিখব:

  • Current object reference
  • Field shadowing
  • this.field
  • Constructor parameters এবং fields-এর same names
  • this() দিয়ে constructor chaining
  • Method overloading
  • Constructor overloading
  • Overload selection
  • Clear এবং non-ambiguous overload design