Object-Oriented Programming Foundations
Static and Instance Members
You are viewing a free preview lesson.
Lesson Overview
একটি class থেকে multiple objects তৈরি করা যায়।
Course javaCourse =
new Course(
"Java and OOP Foundation",
20
);
Course backendCourse =
new Course(
"Backend Development",
30
);
প্রতিটি course-এর নিজস্ব state আছে:
javaCourse:
title = Java and OOP Foundation
totalLessons = 20
backendCourse:
title = Backend Development
totalLessons = 30
এগুলো instance state।
কিন্তু কিছু information কোনো specific object-এর নয়; পুরো class-এর সঙ্গে related।
Examples:
সর্বোচ্চ title length
সব Course objects মিলিয়ে মোট কতটি তৈরি হয়েছে
একটি shared conversion method
এই ধরনের members static হতে পারে।
এই lesson-এ আমরা শিখব:
- Instance fields এবং methods
- Static fields এবং methods
- Object-level এবং class-level state
- Shared counters
static finalconstants- Static context-এর limitations
- Utility methods
- Global mutable state-এর risk
- কোথায়
staticব্যবহার করা উচিত এবং কোথায় avoid করা উচিত
Learning Objectives
এই lesson শেষ করার পর আপনি পারবেন:
- Instance এবং static member-এর পার্থক্য ব্যাখ্যা করতে
- Static field এবং method declare করতে
- Class name দিয়ে static member access করতে
- Per-object state এবং shared state আলাদা করতে
static finalconstant তৈরি করতে- Static method থেকে instance field direct access করা যায় না কেন বুঝতে
- Utility method কখন static হতে পারে তা নির্ধারণ করতে
- Mutable static state-এর risk explain করতে
- Domain state unnecessaryভাবে global করা avoid করতে
Instance Members
যে field বা method কোনো specific object-এর সঙ্গে related, সেটি instance member।
public class Course {
private String title;
private int totalLessons;
private boolean published;
}
এখানে প্রতিটি Course object-এর নিজস্ব:
titletotalLessonspublished
value থাকে।
Independent Instance State
Course javaCourse =
new Course(
"Java and OOP Foundation",
20
);
Course backendCourse =
new Course(
"Backend Development",
30
);
Objects আলাদা state maintain করে।
javaCourse.totalLessons = 20
backendCourse.totalLessons = 30
একটি object change করলে অন্যটি change হয় না।
Instance Methods
Instance method current object-এর state read বা change করতে পারে।
public boolean publish() {
if (published) {
return false;
}
published = true;
return true;
}
Call:
javaCourse.publish();
এই method javaCourse object-এর published field change করে।
অন্য course unchanged থাকে।
What Is a Static Member?
static member কোনো individual object-এর নয়।
এটি class-এর সঙ্গে associated।
public class Course {
private static int totalCoursesCreated;
}
সব Course objects একই static field share করে।
Conceptually:
Course class:
totalCoursesCreated = 2
javaCourse:
title = Java and OOP Foundation
backendCourse:
title = Backend Development
Static Field
Static field declare করতে static keyword ব্যবহার করা হয়।
private static int totalCoursesCreated;
এটির একটি shared value থাকে।
প্রতিটি object-এর আলাদা copy থাকে না।
Counting Created Objects
public class Course {
private static int totalCoursesCreated;
private String title;
private int totalLessons;
public Course(
String title,
int totalLessons
) {
if (
title == null
|| title.isBlank()
) {
throw new IllegalArgumentException(
"Course title is required."
);
}
if (totalLessons <= 0) {
throw new IllegalArgumentException(
"Total lessons must be greater than zero."
);
}
this.title =
title.strip();
this.totalLessons =
totalLessons;
totalCoursesCreated++;
}
}
প্রতিবার constructor successfulভাবে execute হলে shared counter increment হয়।
Accessing a Static Field
Static field class name দিয়ে access করা উচিত।
Course.getTotalCoursesCreated();
Counter expose করার জন্য static query method:
public static int getTotalCoursesCreated() {
return totalCoursesCreated;
}
Usage:
System.out.println(
Course.getTotalCoursesCreated()
);
Complete Counter Example
public class Main {
public static void main(String[] args) {
System.out.println(
Course.getTotalCoursesCreated()
);
Course javaCourse =
new Course(
"Java and OOP Foundation",
20
);
Course backendCourse =
new Course(
"Backend Development",
30
);
System.out.println(
Course.getTotalCoursesCreated()
);
}
}
Output:
0
2
Counter কোনো specific course-এর নয়।
এটি সব তৈরি হওয়া course-এর aggregate information।
Class Name vs Object Reference
Technically Java static member object reference দিয়েও access করতে দিতে পারে:
javaCourse.getTotalCoursesCreated();
কিন্তু এটি misleading।
দেখে মনে হয় valueটি javaCourse object-এর own state।
Preferred:
Course.getTotalCoursesCreated();
Class name ব্যবহার করলে shared nature clear হয়।
Static Methods
Static method class-এর সঙ্গে associated।
public static int getTotalCoursesCreated() {
return totalCoursesCreated;
}
Call:
Course.getTotalCoursesCreated();
Static method call করার জন্য object প্রয়োজন নেই।
Static Method Has No Current Object
Instance method একটি specific object-এর ওপর execute হয়।
javaCourse.publish();
Static method কোনো specific object-এর ওপর execute হয় না।
Course.getTotalCoursesCreated();
তাই static method-এর ভেতরে this available নয়।
Invalid:
public static void displayTitle() {
System.out.println(
this.title
);
}
Compile হবে না।
Static Method Cannot Directly Access Instance Fields
Invalid:
public static String getTitle() {
return title;
}
Problem:
কোন Course object-এর title?
Class-এর multiple objects থাকতে পারে।
javaCourse.title
backendCourse.title
Static method জানে না কোন object use করবে।
Static Method Can Receive an Object
Static method object parameter হিসেবে নিতে পারে।
public static boolean hasSameLessonCount(
Course first,
Course second
) {
return first.totalLessons
== second.totalLessons;
}
এটি compile করতে পারে কারণ method explicit objects পেয়েছে।
তবে methodটি Course class-এর natural responsibility কি না, তা design question।
Usage:
boolean same =
Course.hasSameLessonCount(
javaCourse,
backendCourse
);
Instance Method Can Access Static Members
Instance method static field access করতে পারে।
public int getCreatedCourseCount() {
return totalCoursesCreated;
}
Technically valid।
কিন্তু shared information instance method দিয়ে expose করলে meaning unclear হতে পারে।
Better:
public static int getTotalCoursesCreated() {
return totalCoursesCreated;
}
Member-এর nature এবং access style consistent রাখা ভালো।
Instance vs Static Summary
| Instance Member | Static Member |
|---|---|
| Specific object-এর সঙ্গে related | Class-এর সঙ্গে related |
| প্রতিটি object-এর independent value থাকতে পারে | একটি shared value থাকে |
| Object reference দিয়ে access করা হয় | Class name দিয়ে access করা উচিত |
this available | this available নয় |
| Instance এবং static members access করতে পারে | Instance members direct access করতে পারে না |
Static Constants
Application-wide fixed value-এর জন্য static final commonly used।
public static final int MAX_TITLE_LENGTH =
150;
Keywords:
static → Class-level member
final → Assignment-এর পরে value change করা যাবে না
Constant Naming Convention
Constants সাধারণত uppercase এবং words underscore দিয়ে separated।
MAX_TITLE_LENGTH
DEFAULT_PAGE_SIZE
MIN_COURSE_PRICE
PLATFORM_NAME
Avoid:
maxTitleLength
MaxTitleLength
Using a Constant in Validation
public class Course {
public static final int MAX_TITLE_LENGTH =
150;
private String title;
public Course(
String title
) {
validateTitle(title);
this.title =
title.strip();
}
private static void validateTitle(
String title
) {
if (
title == null
|| title.isBlank()
) {
throw new IllegalArgumentException(
"Course title is required."
);
}
if (
title.strip().length()
> MAX_TITLE_LENGTH
) {
throw new IllegalArgumentException(
"Course title cannot exceed "
+ MAX_TITLE_LENGTH
+ " characters."
);
}
}
}
MAX_TITLE_LENGTH সব course-এর জন্য same rule।
তাই এটি instance field হওয়ার প্রয়োজন নেই।
Why Constants Are Static
Weak:
private final int maxTitleLength =
150;
এতে প্রতিটি object conceptually same configuration carry করছে।
Better:
public static final int MAX_TITLE_LENGTH =
150;
Ruleটি class-level এবং immutable।
Compile-Time Constants
Primitive এবং String values দিয়ে তৈরি কিছু static final fields compile-time constants হতে পারে।
public static final String PLATFORM_NAME =
"LiveKlass";
public static final int MAX_TITLE_LENGTH =
150;
কিন্তু every static final object deeply immutable নয়।
Example:
public static final List<String> TITLES =
new ArrayList<>();
Reference reassign করা যাবে না, কিন্তু list mutate করা যেতে পারে।
Collections শেখার সময় এটি বিস্তারিত আলোচনা করা হবে।
Important:
finalreferenceকে স্থির করে; referenced objectকে automatically immutable করে না।
Static Utility Methods
যে method:
- কোনো object state-এর ওপর depend করে না
- শুধু supplied inputs থেকে result calculate করে
- Class-level operation হিসেবে natural
সেটি static হতে পারে।
Example:
public final class PriceCalculator {
private PriceCalculator() {
}
public static long applyDiscount(
long priceInPaisa,
int discountPercentage
) {
if (priceInPaisa < 0) {
throw new IllegalArgumentException(
"Price cannot be negative."
);
}
if (
discountPercentage < 0
|| discountPercentage > 100
) {
throw new IllegalArgumentException(
"Discount must be between 0 and 100."
);
}
long discountAmount =
priceInPaisa
* discountPercentage
/ 100;
return priceInPaisa
- discountAmount;
}
}
Usage:
long discountedPrice =
PriceCalculator.applyDiscount(
499_000L,
20
);
Why the Utility Constructor Is Private
private PriceCalculator() {
}
PriceCalculator শুধু static utility methods ধারণ করে।
Object তৈরি করার meaningful reason নেই।
Private constructor prevent করে:
new PriceCalculator();
তবে utility class সব problem-এর solution নয়।
যদি behavior domain object-এর own state-এর সঙ্গে naturally related হয়, instance method better হতে পারে।
Instance Method or Static Utility?
Course price-এর discount calculate করতে দুইটি design possible।
Instance Method
public long calculateDiscountedPrice(
int discountPercentage
) {
return PriceCalculator.applyDiscount(
priceInPaisa,
discountPercentage
);
}
Usage:
course.calculateDiscountedPrice(
20
);
এটি natural, কারণ calculation current course price ব্যবহার করছে।
Static Utility
PriceCalculator.applyDiscount(
priceInPaisa,
20
);
এটি useful যখন calculation general এবং কোনো specific domain object-এর ownership নয়।
Design question:
Operationটি কোন object-এর responsibility হিসেবে সবচেয়ে natural?
Static Factory Method
Static method object create করতেও ব্যবহার করা যায়।
public static Course freeCourse(
String title,
int totalLessons
) {
return new Course(
title,
totalLessons,
0
);
}
Usage:
Course javaCourse =
Course.freeCourse(
"Java Fundamentals",
20
);
Constructor call-এর তুলনায় intent clearer:
new Course(
"Java Fundamentals",
20,
0
);
versus:
Course.freeCourse(
"Java Fundamentals",
20
);
Static factory methods:
- Meaningful names দিতে পারে
- Different creation paths express করতে পারে
- Validation centralize করতে পারে
তবে constructors-এর foundation clear হওয়ার পর ব্যবহার করা উচিত।
Static State Is Shared Global State
Static mutable field effectively application-wide shared state হতে পারে।
private static int totalCoursesCreated;
সব callers same value observe এবং potentially modify করতে পারে।
Shared mutable state-এর risks:
- Tests একে অন্যকে affect করতে পারে
- Execution order matter করতে পারে
- Concurrent updates হারিয়ে যেতে পারে
- Hidden dependencies তৈরি হয়
- Debugging কঠিন হয়
- Application restart হলে value reset হয়
তাই mutable static fields carefully ব্যবহার করতে হয়।
A Static Counter Is Not a Database Count
private static int totalCoursesCreated;
এই counter শুধু current Java process-এ constructor calls count করে।
এটি:
- Database-এর total course count নয়
- Multiple application servers-এর combined count নয়
- Restart-এর পরে preserved নয়
- Deleted courses account করে না
- Concurrent updates-এর জন্য automatically safe নয়
Learning example হিসেবে useful।
Production business metric হিসেবে unreliable।
Concurrency Risk
This operation:
totalCoursesCreated++;
একটি simple line হলেও multiple threads-এর মধ্যে atomic guarantee দেয় না।
Concurrent object creation হলে updates হারিয়ে যেতে পারে।
Production counter-এর জন্য alternatives হতে পারে:
AtomicInteger- Database sequence
- Metrics system
- Persistent storage
Concurrency পরে বিস্তারিত শেখানো হবে।
Important engineering lesson:
Shared mutable static state simple দেখালেও production environment-এ hidden complexity তৈরি করে।
Avoid Global Domain State
Poor design:
public class Enrollment {
public static int completedLessons;
}
এখন সব enrollment একই progress share করবে।
subuEnrollment.completeLesson();
এর effect sumuEnrollment-এর progress-এও পড়বে।
Completed lessons একটি specific enrollment-এর state।
তাই এটি instance field হওয়া উচিত।
private int completedLessons;
Questions for Choosing Static or Instance
কোন member static হবে কি না নির্ধারণ করতে প্রশ্ন করুন:
- Valueটি কি specific object অনুযায়ী different?
- Methodটি কি current object state ব্যবহার করে?
- Informationটি কি পুরো class-এর জন্য shared?
- এটি কি immutable constant?
- এটি কি stateless utility calculation?
- Shared mutable state তৈরি হচ্ছে কি?
- Static dependency testing কঠিন করবে কি?
- Valueটি application restart-এর পরে survive করা প্রয়োজন কি?
A Focused Course Example
Course.java
public class Course {
public static final int MAX_TITLE_LENGTH =
150;
private static int totalCoursesCreated;
private final String title;
private final int totalLessons;
private final long priceInPaisa;
private boolean published;
public Course(
String title,
int totalLessons,
long priceInPaisa
) {
validateTitle(title);
if (totalLessons <= 0) {
throw new IllegalArgumentException(
"Total lessons must be greater than zero."
);
}
if (priceInPaisa < 0) {
throw new IllegalArgumentException(
"Price cannot be negative."
);
}
this.title =
title.strip();
this.totalLessons =
totalLessons;
this.priceInPaisa =
priceInPaisa;
this.published = false;
totalCoursesCreated++;
}
public static Course freeCourse(
String title,
int totalLessons
) {
return new Course(
title,
totalLessons,
0
);
}
public static int getTotalCoursesCreated() {
return totalCoursesCreated;
}
private static void validateTitle(
String title
) {
if (
title == null
|| title.isBlank()
) {
throw new IllegalArgumentException(
"Course title is required."
);
}
if (
title.strip().length()
> MAX_TITLE_LENGTH
) {
throw new IllegalArgumentException(
"Course title cannot exceed "
+ MAX_TITLE_LENGTH
+ " characters."
);
}
}
public boolean publish() {
if (published) {
return false;
}
published = true;
return true;
}
public long calculateDiscountedPrice(
int discountPercentage
) {
return PriceCalculator.applyDiscount(
priceInPaisa,
discountPercentage
);
}
public String getTitle() {
return title;
}
public int getTotalLessons() {
return totalLessons;
}
public long getPriceInPaisa() {
return priceInPaisa;
}
public boolean isPublished() {
return published;
}
}
PriceCalculator.java
public final class PriceCalculator {
private PriceCalculator() {
}
public static long applyDiscount(
long priceInPaisa,
int discountPercentage
) {
if (priceInPaisa < 0) {
throw new IllegalArgumentException(
"Price cannot be negative."
);
}
if (
discountPercentage < 0
|| discountPercentage > 100
) {
throw new IllegalArgumentException(
"Discount must be between 0 and 100."
);
}
long discountAmount =
priceInPaisa
* discountPercentage
/ 100;
return priceInPaisa
- discountAmount;
}
}
Main.java
public class Main {
public static void main(String[] args) {
Course javaCourse =
Course.freeCourse(
"Java and OOP Foundation",
20
);
Course backendCourse =
new Course(
"Backend Development",
30,
799_000L
);
backendCourse.publish();
long discountedPrice =
backendCourse
.calculateDiscountedPrice(
20
);
System.out.println(
"Created courses: "
+ Course
.getTotalCoursesCreated()
);
System.out.println(
"Maximum title length: "
+ Course.MAX_TITLE_LENGTH
);
System.out.println(
"Java course price: "
+ javaCourse
.getPriceInPaisa()
);
System.out.println(
"Backend discounted price: "
+ discountedPrice
);
System.out.println(
"Backend published: "
+ backendCourse
.isPublished()
);
}
}
Output:
Created courses: 2
Maximum title length: 150
Java course price: 0
Backend discounted price: 639200
Backend published: true
Engineering Note: Dependency Injection vs Static Calls
Static utility calls simple:
PriceCalculator.applyDiscount(
price,
discount
);
কিন্তু external services static করা problematic হতে পারে।
Avoid:
PaymentGateway.charge(
payment
);
EmailSender.send(
message
);
কারণ:
- Implementation replace করা কঠিন
- Tests-এ fake dependency দেওয়া কঠিন
- Hidden global dependency তৈরি হয়
- Configuration manage করা কঠিন
Stateless pure calculation static হতে পারে।
External collaboration সাধারণত object dependency হিসেবে inject করা better।
এই topic application architecture-এ পরে বিস্তারিত শেখানো হবে।
Common Mistakes
Making Object State Static
Wrong:
private static String title;
সব Course objects একই title share করবে।
Correct:
private String title;
Accessing Static Members Through Objects
Avoid:
course.getTotalCoursesCreated();
Prefer:
Course.getTotalCoursesCreated();
Accessing Instance Fields from Static Methods
Invalid:
public static String getTitle() {
return title;
}
Static method-এর current object নেই।
Using this in Static Context
Invalid:
public static void show() {
System.out.println(this);
}
Making Every Helper Static
Helper current object state-এর natural behavior হলে instance method better।
Using Mutable Static Fields as Persistent Data
Static field restart, multiple servers এবং concurrent execution handle করে না।
Assuming static final Makes an Object Deeply Immutable
final reference reassign prevent করে।
Referenced mutable object still change হতে পারে।
Exposing Mutable Static Fields Publicly
Dangerous:
public static int totalCoursesCreated;
Any caller can assign:
Course.totalCoursesCreated =
-100;
Keep mutable static state private।
Practice Exercises
Exercise 1: Classify Members
নিচের members instance নাকি static হওয়া উচিত নির্ধারণ করুন:
Course title
Course price
Maximum title length
Total objects created
Enrollment progress
Discount calculation using supplied values
Exercise 2: Add a Static Counter
একটি Learner class-এ successful object creation count করুন।
Expose:
public static int getTotalLearnersCreated()
Explain কেন এটি production database count নয়।
Exercise 3: Create a Constant
Create:
public static final int MAX_LESSON_COUNT
Constructor validation-এ constantটি ব্যবহার করুন।
Exercise 4: Fix Static Misuse
public class Enrollment {
private static int completedLessons;
public void completeLesson() {
completedLessons++;
}
}
Explain problem এবং correct implementation লিখুন।
Exercise 5: Static Context
Explain why this does not compile:
public static boolean isPublished() {
return published;
}
Then write an appropriate instance version।
Exercise 6: Utility Method
Create a utility method:
public static long takaToPaisa(
long taka
)
Negative input reject করুন।
Exercise 7: Static Factory
Create:
Course.freeCourse(
String title,
int totalLessons
)
Methodটি constructor reuse করবে।
Exercise 8: Design Decision
Decide whether each operation should be static or instance-based:
- Calculate one enrollment's progress
- Validate a general email format
- Publish a specific course
- Return maximum allowed title length
- Charge a payment through an external gateway
Explain your decisions।
Predict the Result
Question 1
public class Counter {
static int value;
Counter() {
value++;
}
}
new Counter();
new Counter();
System.out.println(
Counter.value
);
Question 2
public class Profile {
String name;
static void printName() {
System.out.println(name);
}
}
Will it compile?
Question 3
public class Settings {
static final int LIMIT = 10;
}
Can this compile?
Settings.LIMIT = 20;
Question 4
public class Enrollment {
static int completedLessons;
}
Two objects update completedLessons।
Will they observe separate values?
Predict the Result Answers
Answer 1
2
Both constructor calls same static field increment করেছে।
Answer 2
না।
Static method কোনো specific Profile object-এর name field identify করতে পারে না।
Answer 3
না।
final field reassign করা যাবে না।
Answer 4
না।
Both objects same shared static value observe করবে।
Knowledge Check
Question 1
Instance field কী?
Question 2
Static field কী?
Question 3
Static member access করার preferred style কী?
Question 4
Static method-এ this নেই কেন?
Question 5
Static method কি instance field direct access করতে পারে?
Question 6
Instance method কি static field access করতে পারে?
Question 7
static final commonly কী represent করে?
Question 8
Constant naming convention কী?
Question 9
Static utility method কখন appropriate?
Question 10
Mutable static state risky কেন?
Question 11
Static counter database count নয় কেন?
Question 12
final reference কি referenced object-কে immutable করে?
Question 13
Static factory method-এর benefit কী?
Question 14
External service calls static করলে testing কঠিন হতে পারে কেন?
Knowledge Check Answers
Answer 1
প্রতিটি object-এর জন্য আলাদা state রাখা field।
Answer 2
Class-এর সঙ্গে associated এবং সব instances-এর মধ্যে shared field।
Answer 3
Class name দিয়ে।
Course.getTotalCoursesCreated();
Answer 4
Static method কোনো specific object-এর ওপর execute হয় না।
Answer 5
না, unless একটি object reference explicitly পাওয়া যায়।
Answer 6
হ্যাঁ।
Answer 7
Class-level immutable constant।
Answer 8
Uppercase words separated by underscores।
MAX_TITLE_LENGTH
Answer 9
যখন operation object state-এর ওপর depend করে না এবং supplied inputs থেকে result calculate করে।
Answer 10
Global coupling, concurrency issues, test interference এবং hidden dependencies তৈরি করতে পারে।
Answer 11
Value process-local, non-persistent, multi-server unaware এবং restart হলে reset হয়।
Answer 12
না। Reference reassign করা যায় না, কিন্তু mutable object-এর content change হতে পারে।
Answer 13
Named creation paths, clearer intent এবং centralized construction logic।
Answer 14
Implementation replace, fake dependency inject এবং isolated test করা কঠিন হয়।
Lesson Summary
এই lesson-এ আমরা শিখেছি:
- Instance members specific object-এর সঙ্গে related
- Static members পুরো class-এর সঙ্গে related
- Instance fields objects-এর independent state রাখে
- Static field সব objects-এর মধ্যে shared
- Static members class name দিয়ে access করা উচিত
- Static method call করার জন্য object প্রয়োজন নেই
- Static context-এ current object এবং
thisনেই - Static method instance fields direct access করতে পারে না
- Instance method static members access করতে পারে
static finalclass-level constants-এর জন্য useful- Constants uppercase underscore naming follow করে
finalreference deep immutability guarantee করে না- Stateless utility calculation static হতে পারে
- Domain behavior current object state-এর সঙ্গে related হলে instance method natural
- Static factory meaningful object creation names দিতে পারে
- Mutable static state global shared state তৈরি করে
- Static counters persistent বা distributed counts নয়
- Concurrent static mutation thread-safety problems তৈরি করতে পারে
- Specific object-এর domain state static করা উচিত নয়
- External services static dependencies হিসেবে ব্যবহার করা testing এবং design দুর্বল করতে পারে
staticconvenience-এর জন্য নয়; ownership এবং lifecycle অনুযায়ী ব্যবহার করা উচিত
Next Lesson
পরবর্তী lesson:
Object References, null, Identity, Equality, and toString()
আমরা শিখব:
- Object reference কী
- Shared references
- Reassigning references
nullNullPointerException- Object identity
==এবংequals()hashCode()contract-এর introduction- Useful
toString()implementation - Safe এবং meaningful object comparison