Object-Oriented Programming Foundations
Classes, Objects, Fields, and Methods
আপনি একটি free preview lesson দেখছেন।
Lesson Overview
In the previous lesson, we learned the core ideas of Object-Oriented Programming:
- Objects hold state
- Objects expose behavior
- Classes define the type and structure of objects
- Responsibility should be placed with the appropriate object
Now we will use Java syntax to build a simple object-oriented model.
Our running example will be a course enrollment.
An enrollment has state such as:
- Learner name
- Course title
- Completed lesson count
- Total lesson count
Behavior:
- Complete a lesson
- Calculate progress
- Determine whether the course is completed
In this lesson, we will access fields directly so that the mechanics of classes and objects remain clear.
This is a temporary learning step.
After learning constructors and encapsulation, object creation and state changes will become more controlled.
Learning Objectives
After completing this lesson, you will be able to:
- Declare a Java class
- Identify fields and instance methods
- Create objects using
new - Understand what a reference variable is
- Access object state using the dot operator
- Call instance methods
- Create multiple objects from the same class
- Understand independent object state
- Explain why reference assignment does not copy an object
- Recognize default field values
- Understand the basic risk of a
nullreference
Declaring a Class
In Java, a class is declared using the class keyword.
public class Enrollment {
}
Here:
public
→ access modifier
class
→ class declaration keyword
Enrollment
→ class name
The class's fields and methods are placed inside the curly braces.
Class Naming
Java class names generally follow PascalCase.
Good:
Enrollment
Course
LearnerProfile
PaymentTransaction
Avoid:
enrollment
learner_profile
paymenttransaction
A class name is usually a meaningful noun or noun phrase.
Fields Represent Object State
Variables declared inside the class body but outside methods are called fields.
public class Enrollment {
String learnerName;
String courseTitle;
int completedLessons;
int totalLessons;
}
These fields represent the state of each Enrollment object.
Example:
Learner: Nur
Course: Java and OOP Foundation
Completed lessons: 16
Total lessons: 20
Methods Represent Object Behavior
Methods inside a class define what an object can do.
public class Enrollment {
String learnerName;
String courseTitle;
int completedLessons;
int totalLessons;
double calculateProgress() {
return completedLessons
* 100.0
/ totalLessons;
}
}
Here:
calculateProgress()
is an instance method.
The method uses the object's fields to calculate progress.
Our First Class
Enrollment.java
public class Enrollment {
String learnerName;
String courseTitle;
int completedLessons;
int totalLessons;
void completeLesson() {
if (
totalLessons <= 0
|| completedLessons >= totalLessons
) {
return;
}
completedLessons++;
}
double calculateProgress() {
if (totalLessons <= 0) {
return 0.0;
}
return completedLessons
* 100.0
/ totalLessons;
}
boolean isCompleted() {
return totalLessons > 0
&& completedLessons
== totalLessons;
}
}
The class defines:
State
learnerName
courseTitle
completedLessons
totalLessons
Behavior
completeLesson()
calculateProgress()
isCompleted()
No specific enrollment has been created yet.
Enrollment is only a type and object definition.
Creating an Object
Use new to create an object.
Enrollment nurEnrollment =
new Enrollment();
General form:
ClassName referenceName =
new ClassName();
Understanding Object Creation
Enrollment nurEnrollment =
new Enrollment();
This can be divided into three important parts.
Type
Enrollment
Defines what kind of object the variable can reference.
Reference Variable
nurEnrollment
Holds the reference to the created object.
Object Creation
new Enrollment()
Creates a new Enrollment object.
A Reference Variable Is Not the Object
Enrollment nurEnrollment =
new Enrollment();
Conceptually:
nurEnrollment
|
v
Enrollment object
nurEnrollment is a reference variable.
The actual state exists inside the object.
Dot Operator
We use . to access an object's fields and methods.
Field:
nurEnrollment.learnerName
Method:
nurEnrollment.calculateProgress()
Assigning Object State
nurEnrollment.learnerName =
"Nur";
nurEnrollment.courseTitle =
"Java and OOP Foundation";
nurEnrollment.completedLessons =
16;
nurEnrollment.totalLessons =
20;
The object's state is now:
Learner: Nur
Course: Java and OOP Foundation
Completed: 16
Total: 20
Reading Object State
System.out.println(
nurEnrollment.learnerName
);
Output:
Nur
And:
System.out.println(
nurEnrollment.completedLessons
);
Output:
16
Calling an Instance Method
double progress =
nurEnrollment.calculateProgress();
System.out.println(progress);
Output:
80.0
because:
16 × 100 ÷ 20 = 80
An Instance Method Can Change State
nurEnrollment.completeLesson();
Before:
completedLessons = 16
After:
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 enrollment =
new Enrollment();
enrollment.learnerName =
"Nur";
enrollment.courseTitle =
"Java and OOP Foundation";
enrollment.completedLessons =
16;
enrollment.totalLessons =
20;
System.out.println(
"Learner: "
+ enrollment.learnerName
);
System.out.println(
"Course: "
+ enrollment.courseTitle
);
System.out.println(
"Progress: "
+ enrollment.calculateProgress()
+ "%"
);
enrollment.completeLesson();
System.out.println(
"Updated progress: "
+ enrollment.calculateProgress()
+ "%"
);
System.out.println(
"Completed: "
+ enrollment.isCompleted()
);
}
}
Output:
Learner: Nur
Course: Java and OOP Foundation
Progress: 80.0%
Updated progress: 85.0%
Completed: false
One Class, Multiple Objects
You can create as many objects as needed from one class.
Enrollment sakibEnrollment =
new Enrollment();
Enrollment jalisaEnrollment =
new Enrollment();
Each:
new Enrollment()
creates a new object.
Objects Have Independent State
sakibEnrollment.learnerName =
"Sakib";
sakibEnrollment.completedLessons =
18;
sakibEnrollment.totalLessons =
20;
jalisaEnrollment.learnerName =
"Jalisa";
jalisaEnrollment.completedLessons =
20;
jalisaEnrollment.totalLessons =
20;
Now:
Sakib
18 / 20
Jalisa
20 / 20
Calls:
System.out.println(
sakibEnrollment.calculateProgress()
);
System.out.println(
jalisaEnrollment.calculateProgress()
);
Output:
90.0
100.0
Updating One Object Does Not Change Another
sakibEnrollment.completeLesson();
Now:
Sakib
19 / 20
Jalisa
20 / 20
jalisaEnrollment has not changed.
They are separate objects.
Same Method, Different Object State
The method implementation is written once in the class:
double calculateProgress() {
// ...
}
But this call:
sakibEnrollment.calculateProgress();
uses Sakib's object state.
And:
jalisaEnrollment.calculateProgress();
uses Jalisa's object state.
The same behavior operates on the state of different objects.
Fields and Local Variables
A field is declared in the class body:
public class Enrollment {
int completedLessons;
}
A local variable is declared inside a method:
double calculateProgress() {
double progress =
completedLessons
* 100.0
/ totalLessons;
return progress;
}
Here:
completedLessons
totalLessons
→ fields
progress
→ local variable
Field vs. Local Variable
| Field | Local Variable |
|---|---|
| Declared in the class body | Declared inside a method or block |
| Represents object state | Represents temporary calculation/data |
| Receives a default value | Must be initialized before use |
| Part of the object | Local state of method execution |
Default Field Values
A new object:
Enrollment enrollment =
new Enrollment();
receives Java default values for fields that are not explicitly assigned.
Common defaults:
| Type | Default |
|---|---|
| Reference type | null |
int | 0 |
long | 0L |
double | 0.0 |
boolean | false |
char | '\u0000' |
Current Enrollment:
learnerName = null
courseTitle = null
completedLessons = 0
totalLessons = 0
Default State Is Not Always Meaningful
This code is valid:
Enrollment enrollment =
new Enrollment();
But the object's state is:
Learner: null
Course: null
Completed: 0
Total: 0
This does not represent a useful enrollment.
The important distinction is:
The fact that Java can create an object does not mean its business state is valid.
In the next lesson, we will use constructors to provide required data during object creation.
Local Variables Do Not Receive Default Values
Invalid:
static void example() {
int number;
System.out.println(
number
);
}
A local variable must be initialized before use.
Correct:
static void example() {
int number = 10;
System.out.println(
number
);
}
Reference Assignment Does Not Copy an Object
Consider:
Enrollment first =
new Enrollment();
first.learnerName =
"Subu";
Enrollment second =
first;
No new Enrollment object is created here.
Conceptually:
first ----\
→ Enrollment object
second ----/
Both references point to the same object.
Shared Object Through Two References
second.learnerName =
"Sumu";
System.out.println(
first.learnerName
);
Output:
Sumu
because first and second access the same object.
Use new When You Need an Independent Object
Enrollment subuEnrollment =
new Enrollment();
Enrollment sumuEnrollment =
new Enrollment();
Now there are two independent objects.
== with Object References
== checks whether references point to the same object.
Enrollment first =
new Enrollment();
Enrollment second =
new Enrollment();
System.out.println(
first == second
);
Output:
false
because two separate objects were created.
Same Reference
Enrollment first =
new Enrollment();
Enrollment second =
first;
System.out.println(
first == second
);
Output:
true
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
Even though the data is similar, the object identities are different.
We will learn logical object equality later.
The null Reference
A reference variable can exist without pointing to any object.
Enrollment enrollment =
null;
Conceptually:
enrollment
→ no object
Calling a Method Through null
Enrollment enrollment =
null;
enrollment.calculateProgress();
At runtime:
NullPointerException
can occur.
There is no actual object on which to invoke the method.
Direct Field Access Is Temporary
In this lesson, we write:
enrollment.completedLessons =
16;
This is useful for learning the mechanics of classes and objects.
However, external code could also write:
enrollment.completedLessons =
-100;
or:
enrollment.completedLessons =
500;
which can make the object's state invalid.
Using behavior can help protect rules:
enrollment.completeLesson();
Later, we will restrict field access and make state changes controlled.
A Class Is a Java Type
A class is both an object definition and a Java type.
Enrollment enrollment;
This means:
enrollment
can hold an Enrollment reference.
The compiler uses that type to determine which members are available.
Example:
enrollment.calculateProgress();
is valid because that method is defined in the Enrollment class.
Common Mistakes
Forgetting new
Wrong:
Enrollment enrollment =
Enrollment();
Correct:
Enrollment enrollment =
new Enrollment();
Not Initializing a Local Reference
Wrong:
Enrollment enrollment;
enrollment.learnerName =
"Nur";
Correct:
Enrollment enrollment =
new Enrollment();
Using a null Reference
Enrollment enrollment =
null;
enrollment.completeLesson();
A NullPointerException can occur at runtime.
Thinking Reference Assignment Copies the Object
Enrollment second =
first;
copies the reference to the same object.
It does not create a new object.
Treating Default Values as Valid Data
Enrollment enrollment =
new Enrollment();
may have:
learnerName = null
totalLessons = 0
which may not represent a business-valid enrollment.
Modifying State Directly Everywhere
Instead of:
enrollment.completedLessons++;
prefer meaningful behavior:
enrollment.completeLesson();
when rules are associated with the state change.
Practice Exercise 1: Create a Course
Create:
public class Course
Fields:
title
lessonCount
published
Method:
boolean canBePublished()
Return true when:
titleis not nulltitleis not blanklessonCount > 0
Practice Exercise 2: Create Two Objects
Create two independent Course objects:
Java and OOP Foundation
Backend Development with Spring Boot
Assign different lesson counts.
Update one object and verify that the other remains unchanged.
Practice Exercise 3: Enrollment Progress
Create an Enrollment object.
State:
Learner: Sakib
Completed lessons: 18
Total lessons: 20
Print:
- Progress
- Completion status
Practice Exercise 4: Reference Assignment
Predict 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.
Practice Exercise 5: Independent Identity
Create two separate objects:
Enrollment first =
new Enrollment();
Enrollment second =
new Enrollment();
Give them the same data.
Then predict the result of:
first == second
Practice Exercise 6: Protect the State Change
Write completeLesson() so that:
- If
totalLessons <= 0, it does nothing - If all lessons are already completed, it does nothing
- Otherwise, it increments
completedLessonsby one
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;
enrollment.calculateProgress();
Predict the Output Answers
Answer 1
0
The default value of an int field is 0.
Answer 2
true
Both references point to the same object.
Answer 3
false
Two separate objects were created.
Answer 4
6
completeLesson() updated the state.
Answer 5
At runtime:
NullPointerException
can occur.
Knowledge Check
Question 1
What is a class?
Question 2
What is an object?
Question 3
What does a field represent?
Question 4
What does an instance method represent?
Question 5
What does new do?
Question 6
What is a reference variable?
Question 7
What is the dot operator used for?
Question 8
Can two objects from the same class have independent state?
Question 9
Why can the same method return different results for different objects?
Question 10
Do fields receive default values?
Question 11
Do local variables receive automatic default values?
Question 12
Does reference assignment copy an object?
Question 13
For object references, what does == check?
Question 14
What does null mean?
Question 15
What can happen if an instance method is called through a null reference?
Knowledge Check Answers
Answer 1
A custom Java type that defines the state structure and behavior of objects.
Answer 2
An actual instance of a class.
Answer 3
The object's state or data.
Answer 4
The object's behavior.
Answer 5
It creates a new object and produces a reference to it.
Answer 6
A variable that holds a reference to an object.
Answer 7
To access an object's fields and methods.
Answer 8
Yes.
Answer 9
Each call operates on the fields of that specific object.
Answer 10
Yes.
Answer 11
No. They must be initialized before use.
Answer 12
No. It copies the reference value.
Answer 13
Whether the two references point to the same object.
Answer 14
The reference does not point to any object.
Answer 15
NullPointerException
can occur.
Lesson Summary
In this lesson, we learned:
- A class is a Java type and object definition
- Fields represent object state
- Instance methods represent object behavior
newcreates a new object- A reference variable stores a reference to an object
- The
.operator is used to access fields and methods - Multiple independent objects can be created from one class
- The same instance method uses each object's own state
- Fields receive default values
- Default field values do not guarantee business-valid state
- Local variables do not receive automatic default values
- Reference assignment does not create a new object
- Multiple references can point to the same object
==compares object identitynullmeans that a reference points to no object- Accessing a member through a null reference can cause
NullPointerException - Direct field access is currently being used for learning purposes
- Meaningful methods can help protect state-changing rules