Java13: Encapsulation

Encapsulation is a process of wrapping data and procedures together as a single unit. This is achieved by making all the data private and providing access to these data via public methods.

Private data is only accessible within the class it belongs to. A public member can be accessed from anywhere.

Encapsulation gives more control over data. All data is hidden and prevents direct access to it, this is called data hiding. Testing an encapsulated class is easier. We can make a class read-only or write-only.

Example

class Student{
    private String name;
    private double point;

    public String getName(){
        return this.name;
    }
    public void setName(String name){
        this.name = name;
    }

    public double getPoint(){
        return this.point;
    }
    public void setPoint(double point){
        this.pointer = point;
    }
}

Student class has two private data: name and point. the name data is accessed using two methods: getName() and setName() one method returns the value of name data and the other sets a value name data. the point data is accessed using two methods: getPoint() and setPoint(), one method to return the point and another to set the value to the point data. These pair of methods are called the setter and getter methods.

Next, let's see the StudentDemo class that sets the value to the data and later gets these values to be displayed.

class StudentDemo{
    public static void main(String[] args){
        Student s = new Student();
        s.setName("Albert");
        s.setPoint(3.8);

        String out = "Name : " + s.getName() + "\nPoint : " + s.getPoint();
        System.out.println(out);
    }
}
Output
Name : Albert
Point : 3.8

The getter method does have any parameters and returns a value. Its return type is the same as the data type of the value it is returning. It has a return statement in its method body.

The setter method is a void method and has one parameter. The parameter type is the same as the data type of the field it is modifying. Its method body has an assignment statement.

Both the getter and setter methods give more control over the data. For example, if we want to make sure the point value is between 0 and 4:

public void setPoint(double point){
    if(point >= 0 && point <= 4){
        this.pointer = point;
    }
}

We can make a class read-only by providing only the getter methods for its data. The setter methods can be omitted. Similarly, we can only provide setter methods for its data if we want to make the class write-only.

A post by Cuber

Comments

Popular posts from this blog

Drawing Simple Pie Chart

VB.net connecting to SQL Server

VB.net