Õppetund 38/140
Kirjalik õppetund · 13 min

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.

Eelvaade

Vaatad tasuta eelvaate õppetundi.

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 null reference

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:

java
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:

java
public class Enrollment {

    String learnerName;
    String courseTitle;

    int completedLessons;
    int totalLessons;
}

These fields represent the state of each Enrollment object, for example:

text
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:

java
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

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:

java
Enrollment nurEnrollment = new Enrollment();

General form:

java
ClassName referenceName = new ClassName();

Understanding Object Creation

The statement Enrollment nurEnrollment = new Enrollment(); 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

Conceptually:

text
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

java
nurEnrollment.learnerName = "Nur";
nurEnrollment.courseTitle = "Java and OOP Foundation";
nurEnrollment.completedLessons = 16;
nurEnrollment.totalLessons = 20;

The object's state is now:

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

Reading Object State

java
System.out.println(nurEnrollment.learnerName);
System.out.println(nurEnrollment.completedLessons);

Output:

text
Nur
16

Calling an Instance Method

java
double progress = nurEnrollment.calculateProgress();
System.out.println(progress);

Since 16 × 100 ÷ 20 = 80, the output is:

text
80.0

An Instance Method Can Change State

java
nurEnrollment.completeLesson();

Before the call, completedLessons is 16; after it, completedLessons is 17. Updated progress:

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

Output:

text
85.0

Complete Usage Example

Main.java

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:

text
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.

java
Enrollment sakibEnrollment = new Enrollment();
Enrollment jalisaEnrollment = new Enrollment();

Objects Have Independent State

java
sakibEnrollment.learnerName = "Sakib";
sakibEnrollment.completedLessons = 18;
sakibEnrollment.totalLessons = 20;
jalisaEnrollment.learnerName = "Jalisa";
jalisaEnrollment.completedLessons = 20;
jalisaEnrollment.totalLessons = 20;

Now:

text
Sakib
18 / 20

Jalisa
20 / 20

Calls:

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

Output:

text
90.0
100.0

Updating One Object Does Not Change Another

java
sakibEnrollment.completeLesson();

Now:

text
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:

java
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:

java
public class Enrollment {

    int completedLessons;
}

A local variable is declared inside a method:

java
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

FieldLocal Variable
Declared in the class bodyDeclared inside a method or block
Represents object stateRepresents temporary calculation/data
Receives a default valueMust be initialized before use
Part of the objectLocal 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:

TypeDefault
Reference typenull
int0
long0L
double0.0
booleanfalse
char'\u0000'

Default State Is Not Always Meaningful

The code Enrollment enrollment = new Enrollment(); is valid, but the object's state is:

text
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:

java
static void example() {
    int number;
    System.out.println(number);
}

The compiler reports:

text
error: variable number might not have been initialized

A local variable must be initialized before use. Correct:

java
static void example() {
    int number = 10;
    System.out.println(number);
}

Reference Assignment Does Not Copy an Object

Consider:

java
Enrollment first = new Enrollment();
first.learnerName = "Subu";
Enrollment second = first;

No new Enrollment object is created here. Conceptually:

Diagrammi joonistamine…

Both references point to the same object.

Shared Object Through Two References

java
second.learnerName = "Sumu";
System.out.println(first.learnerName);

Because first and second access the same object, the output is:

text
Sumu

Use new When You Need an Independent Object

Calling new twice creates two independent objects:

java
Enrollment subuEnrollment = new Enrollment();
Enrollment sumuEnrollment = new Enrollment();

== with Object References

== checks whether two references point to the same object:

java
Enrollment first = new Enrollment();
Enrollment second = new Enrollment();
Enrollment third = first;
System.out.println(first == second);
System.out.println(first == third);

Output:

text
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

java
Enrollment first = new Enrollment();
first.learnerName = "Nur";
Enrollment second = new Enrollment();
second.learnerName = "Nur";
System.out.println(first == second);

Output:

text
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:

java
Enrollment enrollment = null;

Conceptually:

text
enrollment
→ no object

Calling a Method Through null

java
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:

java
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:

java
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

java
Enrollment enrollment = new Enrollment();
System.out.println(enrollment.completedLessons);

Answer

text
0

The default value of an int field is 0.

Question 2

java
Enrollment first = new Enrollment();
Enrollment second = first;
System.out.println(first == second);

Answer

text
true

Both references point to the same object.

Question 3

java
Enrollment first = new Enrollment();
Enrollment second = new Enrollment();
System.out.println(first == second);

Answer

text
false

Two separate objects were created.

Question 4

java
Enrollment enrollment = new Enrollment();
enrollment.completedLessons = 5;
enrollment.totalLessons = 10;
enrollment.completeLesson();
System.out.println(enrollment.completedLessons);

Answer

text
6

completeLesson() updated the state.

Question 5

java
Enrollment enrollment = null;
enrollment.calculateProgress();

Answer

The code compiles, but at runtime it throws:

text
NullPointerException

enrollment does not point to an object.

Common Mistakes

Forgetting new

Wrong (does not compile):

java
Enrollment enrollment = Enrollment();

Correct:

java
Enrollment enrollment = new Enrollment();

Not Initializing a Local Reference

Wrong:

java
Enrollment enrollment;
enrollment.learnerName = "Nur";

This does not compile: variable enrollment might not have been initialized. Correct:

java
Enrollment enrollment = new Enrollment();

Modifying State Directly Everywhere

Instead of:

java
enrollment.completedLessons++;

prefer meaningful behavior when rules are associated with the state change:

java
enrollment.completeLesson();

Practice Exercise 1: Create a Course

Solutions: lesson 3.13.

Create public class Course with the fields:

text
title
lessonCount
published

Add the method boolean canBePublished(). Return true when:

  • title is not null
  • title is not blank
  • lessonCount > 0

Practice Exercise 2: Create Two Objects

Create two independent Course objects:

text
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:

text
Learner: Sakib
Completed lessons: 18
Total lessons: 20

Print:

  • Progress
  • Completion status

Practice Exercise 4: Reference Assignment

Predict the output:

java
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:

java
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 completedLessons by 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); new creates 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.
  • null means no object; calling a method through it throws a NullPointerException.
  • Direct field access is temporary; meaningful methods such as completeLesson() protect state-changing rules.

Mõtle enne

Tulekul

Kontrollküsimused, mille puhul valid vastuse enne, kui õppetund selle näitab.