Classes, Objects, Fields, and Methods
Declare a class with fields and instance methods, create objects with `new`, and see how reference variables point to independent objects.
You are viewing a free preview lesson.
Lesson Overview
In the previous lesson, we saw that objects hold state and expose behavior, and that classes define them. Now we turn those ideas into Java syntax. Our running example is a course enrollment: it knows the learner's name, the course title and how many of its lessons are completed, and it can complete a lesson, calculate progress and tell whether the course is completed.
In this lesson, we access fields directly so that the mechanics of classes and objects stay clear. This is a temporary learning step: after constructors and encapsulation, object creation and state changes 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, and the class's fields and methods are placed inside its curly braces:
public class Enrollment {
}
Here, public is an access modifier, class is the class declaration keyword, and Enrollment is the class name.
Class Naming
Java class names generally follow PascalCase, and a class name is usually a meaningful noun or noun phrase: Enrollment, Course, LearnerProfile, PaymentTransaction. Avoid names such as enrollment, learner_profile or paymenttransaction.
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, for 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
The statement Enrollment nurEnrollment = new Enrollment(); can be divided into three important parts:
- Type —
Enrollmentdefines what kind of object the variable can reference. - Reference variable —
nurEnrollmentholds the reference to the created object. - Object creation —
new Enrollment()creates a newEnrollmentobject.
A Reference Variable Is Not the Object
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: nurEnrollment.learnerName accesses a field, and nurEnrollment.calculateProgress() calls a method.
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);
System.out.println(nurEnrollment.completedLessons);
Output:
Nur
16
Calling an Instance Method
double progress = nurEnrollment.calculateProgress();
System.out.println(progress);
Since 16 × 100 ÷ 20 = 80, the output is:
80.0
An Instance Method Can Change State
nurEnrollment.completeLesson();
Before the call, completedLessons is 16; after it, completedLessons is 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. Each new Enrollment() creates a new object.
Enrollment sakibEnrollment = new Enrollment();
Enrollment jalisaEnrollment = new Enrollment();
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 the 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 and totalLessons are fields, and progress is a 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 created with 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' |
Default State Is Not Always Meaningful
The code Enrollment enrollment = new Enrollment(); is valid, but the object's state is:
learnerName = null
courseTitle = null
completedLessons = 0
totalLessons = 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
This does not compile:
static void example() {
int number;
System.out.println(number);
}
The compiler reports:
error: variable number might not have been initialized
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:
Drawing diagram…
Both references point to the same object.
Shared Object Through Two References
second.learnerName = "Sumu";
System.out.println(first.learnerName);
Because first and second access the same object, the output is:
Sumu
Use new When You Need an Independent Object
Calling new twice creates two independent objects:
Enrollment subuEnrollment = new Enrollment();
Enrollment sumuEnrollment = new Enrollment();
== with Object References
== checks whether two references point to the same object:
Enrollment first = new Enrollment();
Enrollment second = new Enrollment();
Enrollment third = first;
System.out.println(first == second);
System.out.println(first == third);
Output:
false
true
first and second refer to two separate objects, while third refers to the same object as first.
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();
This compiles, but at runtime the program stops with a NullPointerException. 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;
enrollment.completedLessons = 500;
which can make the object's state invalid. Using behavior such as enrollment.completeLesson() can help protect rules. 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. This declaration means that enrollment can hold an Enrollment reference:
Enrollment enrollment;
The compiler uses that type to determine which members are available. For example, enrollment.calculateProgress() is valid because that method is defined in the Enrollment class.
Predict the Result
Question 1
Enrollment enrollment = new Enrollment();
System.out.println(enrollment.completedLessons);
Answer
0
The default value of an int field is 0.
Question 2
Enrollment first = new Enrollment();
Enrollment second = first;
System.out.println(first == second);
Answer
true
Both references point to the same object.
Question 3
Enrollment first = new Enrollment();
Enrollment second = new Enrollment();
System.out.println(first == second);
Answer
false
Two separate objects were created.
Question 4
Enrollment enrollment = new Enrollment();
enrollment.completedLessons = 5;
enrollment.totalLessons = 10;
enrollment.completeLesson();
System.out.println(enrollment.completedLessons);
Answer
6
completeLesson() updated the state.
Question 5
Enrollment enrollment = null;
enrollment.calculateProgress();
Answer
The code compiles, but at runtime it throws:
NullPointerException
enrollment does not point to an object.
Common Mistakes
Forgetting new
Wrong (does not compile):
Enrollment enrollment = Enrollment();
Correct:
Enrollment enrollment = new Enrollment();
Not Initializing a Local Reference
Wrong:
Enrollment enrollment;
enrollment.learnerName = "Nur";
This does not compile: variable enrollment might not have been initialized. Correct:
Enrollment enrollment = new Enrollment();
Modifying State Directly Everywhere
Instead of:
enrollment.completedLessons++;
prefer meaningful behavior when rules are associated with the state change:
enrollment.completeLesson();
Practice Exercise 1: Create a Course
Solutions: lesson 3.13.
Create public class Course with the fields:
title
lessonCount
published
Add the 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 with this 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
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
A NullPointerException is thrown at runtime.
Lesson Summary
- A class is a Java type that defines state (fields) and behavior (instance methods);
newcreates an object from it. - A reference variable holds a reference to an object, and the
.operator accesses its fields and methods. - Each object has independent state, so the same instance method gives different results for different objects.
- Fields receive default values, but default values are not business-valid state; local variables must be initialized before use.
- Reference assignment copies the reference, not the object, and
==checks whether two references point to the same object. nullmeans no object; calling a method through it throws aNullPointerException.- Direct field access is temporary; meaningful methods such as
completeLesson()protect state-changing rules.
Think first
Coming soonCheckpoint questions that ask you to commit to an answer before the lesson shows it.