Java Example: Data Encapsulation

Java

Java is an object-oriented programming (OOP) language. There are three fundamental principles that supported by OOP language:

  • Data encapsulation
  • Inheritance
  • Polymorphism

In this tutorial, we’ll explain what is data encapsulation and show you some examples of how to apply data encapsulation in Java application.

What We Used

Data Encapsulation

Data encapsulation also known as information hiding. It is hiding irrelevant information from the users of a class and exposing the relevant information.

The instance variables will be hidden from other classes and only can be accessed via getter methods or setter methods rather than directly access the instance variables.

Info:

  • Getter methods: It also known as accessor methods. The methods will return the variable value of the object.
  • Setter methods: It also known as mutator methods. The methods will update the variable value of the object.

Advantages

  • It can make the variables of class become write-only or read-only fields by using the setter or getter method.
  • It can control over what kind of data will be stored in the variables.
  • It can improve the maintainability and flexibility of the code. The variables of class are accessed by other classes via setter and getter methods. Thus, the implementation code of the methods can be changed at anytime without breaking the classes that use the methods.

How to Implement

  • Keep instance variables protected with private access modifier.
  • Create public setter and getter methods for users to use to access the instance variables.
  • Use the JavaBeans naming convention of set<variableName> for setter methods and get<variableName> for the getter methods.

Java Code Example

Student.java

package com.chankok.oop;

public class Student {

    private String name;
    private String subject;
    private int marks;

    public Student() {
        this.name = "Default Student Name";
    }

    public String getName() {
        return name;
    }

    public void setName(String name) throws Exception {
        if (name == null) {
            // Not allow to set student name as null value
            throw new IllegalArgumentException("Student name cannot be null");
        }
        this.name = name;
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public int getMarks() {
        return marks;
    }

    public void setMarks(int marks) {
        if (marks < 0) {
            // Not allow to set student marks as negative value, assign default value
            this.marks = 0;
        } else {
            this.marks = marks;
        }
    }

}

In Student.java, all the instance variables are private and only can be accessed via getter and setter methods. The implementation of the method setName(String name) and method setMarks(int marks) are used to control the data that stored in the object.

DataEncapsulationExample.java

package com.chankok.oop;

public class DataEncapsulationExample {

    public static void main(String[] args) {

        try {

            Student student1 = new Student();
            student1.setName("Chankok");
            student1.setSubject("History");
            student1.setMarks(-1);

            System.out.println("Student 1 Name: " + student1.getName());
            System.out.println("Student 1 Subject: " + student1.getSubject());
            System.out.println("Student 1 Marks: " + student1.getMarks());

            Student student2 = new Student();
            student2.setName(null);
            student2.setSubject("Mathematics");
            student2.setMarks(50);

            System.out.println("Student 2 Name: " + student2.getName());
            System.out.println("Student 2 Subject: " + student2.getSubject());
            System.out.println("Student 2 Marks: " + student2.getMarks());

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

Output

Student 1 Name: Chankok
Student 1 Subject: History
Student 1 Marks: 0
java.lang.IllegalArgumentException: Student name cannot be null
        at com.chankok.oop.Student.setName(Student.java:20)
        at com.chankok.oop.DataEncapsulationExample.main(DataEncapsulationExample.java:19)

Summary

Congratulation! You have learned what is data encapsulation and how to implement the data encapsulation in Java.

Other Resources