Java Programming - Lesson 16

Java Encapsulation Explained: Private Fields, Getters, Setters and toString()

Watch the accompanying video tutorial via the link below:

https://youtu.be/I3yiL2qtyFg?si=RzGOjXRHNbARkUF7

Introduction

One of the fundamental principles of Object-Oriented Programming (OOP) is encapsulation.

Encapsulation is the practice of combining data and the methods that operate on that data within a class while controlling how other parts of a program access and modify the internal data.

In Java, encapsulation is commonly implemented by declaring fields as private and providing public methods through which other classes can interact with those fields.

Why is this important?

Imagine developing a calendar application. If other parts of your program are allowed to change a date's day, month and year independently, they could accidentally create an impossible date, such as 30 February.

Encapsulation helps prevent such problems by ensuring that an object controls how its internal data is modified.

In this tutorial, you will learn:

What encapsulation means.

Why encapsulation is important.

How to use the private access modifier.

How getter and setter methods work.

How to protect an object's internal state.

How to override the toString() method.

The difference between static and instance methods.

How to implement encapsulation in a complete Java program.

Let's get started!

1. What Is Encapsulation in Java?

Encapsulation is an OOP principle that protects an object's internal data by restricting direct access to its fields and providing controlled methods for interacting with that data.

In simple terms, encapsulation means:

Keeping an object's internal data protected and allowing access through methods designed by the class.

For example, consider a class called Date.

A date object contains three important pieces of information:

Day

Month

Year

We could initially declare the class as follows:

public class CalendarDate {


    public int day;

    public int month;

    public int year;

}


This allows other classes to access and modify all three fields directly.

For example:

CalendarDate meetingDate = new CalendarDate();


meetingDate.day = 29;

meetingDate.month = 2;

meetingDate.year = 2012;


However, this approach creates a problem.

Someone could accidentally write:

meetingDate.day = 30;


The resulting date would be 30 February 2012, which is invalid.

The problem is not that Java cannot store the number 30 in the day field. The problem is that the program does not enforce the rules required for a valid calendar date.

Encapsulation provides a better approach.

2. Understanding the Private Access Modifier

Java provides several access modifiers, including:

public

private

protected

For encapsulation, the private modifier is particularly important.

A private field can only be accessed directly from within the class where it is declared.

Let's modify our previous example:

public class CalendarDate {


    private int day;

    private int month;

    private int year;

}


Now, the fields are protected from direct access by unrelated external classes.

For example, the following code will produce a compilation error:

CalendarDate meetingDate = new CalendarDate();


meetingDate.day = 30;


Why?

Because day is private.

However, methods declared inside the CalendarDate class can still access and modify it.

This means the class can control how its internal data is used.

Important: Private fields are not inaccessible to the entire program. They are inaccessible through direct field access from outside their declaring class. Public methods can still provide controlled access to their values.

3. Understanding Getter Methods

Once we make fields private, other classes cannot read them directly.

However, we may still need to retrieve their values.

This is where getter methods become useful.

A getter is a public method that returns the value of a private field.

Example:

public int getDay() {

    return day;

}


public int getMonth() {

    return month;

}


public int getYear() {

    return year;

}


We can now retrieve the date components through these methods:

System.out.println(meetingDate.getDay());

System.out.println(meetingDate.getMonth());

System.out.println(meetingDate.getYear());


The important difference is that we are accessing the values through methods rather than accessing the fields directly.

This allows the class to retain control over its internal implementation.

Getter Naming Convention

Java commonly uses the following naming convention:

getDay()

getMonth()

getYear()

getName()

getAddress()

The word get is followed by the field name, with its first letter capitalised.

For boolean fields, Java commonly uses is:

public boolean isActive() {

    return active;

}


4. Understanding Setter Methods

Getter methods retrieve values, while setter methods are used to modify them.

For example:

public void setName(String name) {

    this.name = name;

}


Here, setName() allows another part of the program to change the object's name.

The expression:

this.name = name;


means that the parameter name is assigned to the current object's instance field called name.

However, setter methods should not simply accept every value without checking whether it is valid.

For example, a person's age should not normally be negative.

A safer setter would be:

public void setAge(int age) {


    if (age < 0) {

        throw new IllegalArgumentException(

            "Age cannot be negative."

        );

    }


    this.age = age;

}


This method validates the supplied value before modifying the object's internal state.

Important Point

Encapsulation does not mean that every private field must have both a getter and a setter.

Sometimes, an object should allow a value to be read but not directly changed.

In other cases, the class may provide a special operation instead of a general setter.

For example, a bank account should not necessarily expose a method that allows anyone to assign an arbitrary balance. It is safer to provide controlled operations such as deposit() and withdraw().

5. Using Methods to Protect an Object's Internal State

Let's return to our date example.

Instead of allowing external code to modify the day directly, we can provide a method called nextDay().

The method will contain the rules required to calculate the next valid calendar date.

For example:

meetingDate.nextDay();


If the date is 29 February 2012, the method should produce 1 March 2012.

The caller does not need to understand the internal calculations.

It simply requests that the object advance by one day.

This is one of the major benefits of encapsulation: the class is responsible for protecting and managing its own internal state.

6. Understanding the toString() Method

Java provides a special method called toString() through the Object class.

Since all Java classes ultimately inherit from Object, every class has access to this method unless it overrides it.

The default implementation does not normally provide a useful human-readable description of an object.

We can override it to define how our object should appear when converted into text.

For example:

@Override

public String toString() {

    return month + "/" + day + "/" + year;

}


The method returns a string containing the month, day and year.

Suppose our object represents 1 March 2012.

We can display it as follows:

System.out.println(meetingDate);


Output:

3/1/2012


Why Does Java Call toString() Automatically?

Consider:

System.out.println("Meeting date: " + meetingDate);


Because a string is being concatenated with an object, Java obtains the object's textual representation by calling toString().

Conceptually, this behaves like:

System.out.println(

    "Meeting date: " + meetingDate.toString()

);


The @Override annotation tells the compiler that we intend to replace the inherited implementation of toString().

It also helps the compiler detect mistakes, such as using an incorrect method signature.

7. Complete Practical Example: An Encapsulated CalendarDate Class

Let's combine what we have learned into a practical Java application.

Our program will:

Create a date object.

Keep its fields private.

Initialise the fields through a constructor.

Validate the date.

Provide getter methods.

Provide a nextDay() method.

Override toString() to display the date.

Step 1: Create the CalendarDate Class

public class CalendarDate {


    private int day;

    private int month;

    private int year;


    public CalendarDate(int month, int day, int year) {


        if (year < 1) {

            throw new IllegalArgumentException(

                "Year must be positive."

            );

        }


        if (month < 1 || month > 12) {

            throw new IllegalArgumentException(

                "Month must be between 1 and 12."

            );

        }


        if (day < 1 || day > daysInMonth(month, year)) {

            throw new IllegalArgumentException(

                "Invalid day for the given month and year."

            );

        }


        this.month = month;

        this.day = day;

        this.year = year;

    }


    public int getDay() {

        return day;

    }


    public int getMonth() {

        return month;

    }


    public int getYear() {

        return year;

    }


    public static boolean isLeapYear(int year) {


        return (year % 4 == 0 && year % 100 != 0)

                || year % 400 == 0;

    }


    public static int daysInMonth(int month, int year) {


        switch (month) {


            case 1:

            case 3:

            case 5:

            case 7:

            case 8:

            case 10:

            case 12:

                return 31;


            case 4:

            case 6:

            case 9:

            case 11:

                return 30;


            case 2:

                return isLeapYear(year) ? 29 : 28;


            default:

                throw new IllegalArgumentException(

                    "Invalid month."

                );

        }

    }


    public void nextDay() {


        day++;


        if (day > daysInMonth(month, year)) {


            day = 1;

            month++;


            if (month > 12) {

                month = 1;

                year++;

            }

        }

    }


    @Override

    public String toString() {

        return month + "/" + day + "/" + year;

    }

}


Step 2: Create the Main Application Class

Create another class called DateDemo:

public class DateDemo {


    public static void main(String[] args) {


        CalendarDate meetingDate =

                new CalendarDate(2, 29, 2012);


        System.out.println(

            "Original meeting date: " + meetingDate

        );


        meetingDate.nextDay();


        System.out.println(

            "Next meeting date: " + meetingDate

        );


        System.out.println(

            "Day: " + meetingDate.getDay()

        );


        System.out.println(

            "Month: " + meetingDate.getMonth()

        );


        System.out.println(

            "Year: " + meetingDate.getYear()

        );

    }

}


Expected Output

Original meeting date: 2/29/2012

Next meeting date: 3/1/2012

Day: 1

Month: 3

Year: 2012


Understanding What Happened

First, we created a date object:

CalendarDate meetingDate =

        new CalendarDate(2, 29, 2012);


The constructor validated the supplied values before assigning them to the private fields.

Next, we printed the object:

System.out.println(meetingDate);


Java automatically called the overridden toString() method.

We then advanced the date:

meetingDate.nextDay();


The method correctly changed the date from 29 February 2012 to 1 March 2012.

Finally, we retrieved the individual date components using getter methods.

Notice that the program never directly accesses day, month or year.

This is encapsulation in practice.

8. Understanding Static and Instance Methods in This Example

You may have noticed that the example contains both static and non-static methods.

Consider:

public void nextDay()


This is an instance method because it modifies the fields belonging to a particular date object.

We therefore call it through an object:

meetingDate.nextDay();


Now consider:

public static boolean isLeapYear(int year)


This is a static method because determining whether a supplied year is a leap year does not require an existing date object.

We can call it through the class:

CalendarDate.isLeapYear(2024);


The same principle applies to daysInMonth().

This distinction helps us decide which operations belong to an individual object and which operations can be performed independently of one.

9. Benefits of Encapsulation in Java

Encapsulation provides several important benefits.

A. Data Protection

Private fields prevent unrelated classes from directly modifying an object's internal data.

B. Data Validation

Methods can check supplied values before accepting them.

For example, a date class can reject impossible dates.

C. Easier Maintenance

The internal implementation of a class can be changed without necessarily requiring changes to every part of the program that uses it.

D. Improved Organisation

Data and the operations that manage that data remain together in one class.

E. Reusability

A well-designed class can be used in different applications without requiring other programmers to understand every detail of its internal implementation.

F. Controlled Access

The programmer decides which operations should be available to other classes.

10. Practical Exercises

Try these exercises to test your understanding.

Exercise 1: Encapsulating a Student Class

Create a class called Student with the following private fields:

Name

Age

Course

Create public getter methods to retrieve the values.

Exercise 2: Creating Setter Methods

Add setter methods that allow the student's name and course to be changed.

Make sure the age setter rejects negative values.

Exercise 3: Bank Account

Create a class called BankAccount containing a private balance field.

Provide:

A deposit() method.

A withdraw() method.

A getBalance() method.

Prevent withdrawals that exceed the available balance.

Exercise 4: Overriding toString()

Override the toString() method in your Student class to display the student's information in a readable format.

Exercise 5: Date Validation

Modify the CalendarDate example to test the following dates:

29 February 2024.

29 February 2023.

31 April 2025.

31 December 2025.

Observe which dates are accepted and which are rejected.

Conclusion

Encapsulation is one of the foundations of good object-oriented programming.

By declaring fields as private and providing controlled methods for accessing and modifying them, we can protect objects from invalid or unintended changes.

We have also learned how getter methods retrieve private values, how methods such as nextDay() co

ntrol an object's behaviour, and how toString() provides a readable representation of an object.

As you continue learning Java, remember that a well-designed object should not expose its internal data unnecessarily. It should provide clear and meaningful ways for other parts of the program to interact with it.

The goal of encapsulation is not simply to hide data; it is to protect the integrity of an object's state.


Comments