Java Encapsulation

Encapsulation is a technique for making the properties in a class private, hiding the data from other class so others cannot modify the property value directly. To access the properties, it will have to go through the public methods such as getter and setter methods. Encapsulation is one of the fundamentals of Object Oriented Programming, just like Inheritance, Abstract, Polymorphism
and Interface. One main purpose of Encapsulation is to maintain data integrity. For more benefits of encapsulation, Google
for the purpose of encapsulation:)

An example of Encapsulation

public class Student {
    
    /*
     * fields declared private 
     * only accessible through
     * getters and setters
     */
    private String firstName;
    private String lastName;
    private String studentID;
    private int age;
    private double GPA;

    //setters
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public void setStudentID(String studentID) {
        this.studentID = studentID;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public void setGPA(double GPA) {
        this.GPA = GPA;
    }
    
    
    //getters
    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public String getStudentID() {
        return studentID;
    }

    public int getAge() {
        return age;
    }

    public double getGPA() {
        return GPA;
    }
    
}

Test the encapsulation

public class TestEncapsulation {
    
    public static void main(String args[])
    {
        Student s = new Student();
        
        s.setFirstName("Jim");
        s.setLastName("Li");
        s.setStudentID("1889026");
        s.setAge(21);
        s.setGPA(3.3);
        
        System.out.println("First Name: "+s.getFirstName());
        System.out.println("Last Name : "+s.getLastName());
        System.out.println("Student ID: "+s.getStudentID());
        System.out.println("Age       : "+s.getAge());
        System.out.println("GPA       : "+s.getGPA());
    }
    
}

The output

    First Name: Jim
    Last Name : Li
    Student ID: 1889026
    Age : 21
    GPA : 3.3

Search within Codexpedia

Custom Search

Search the entire web

Custom Search