Data Hiding in Java

Data hiding is a technique used in objected oriented programming to hide data members of the class. hiding data members means no one from outside can directly access data members or modified data members. For accessing data external person needs to go through authentication or validation. data hiding increases the data security.

for example, Instagram users can see their inbox or chat box only after providing a proper username and password.

example java code for data hiding-

package gangforcode;

public class dataHiding {
    private String name;  
    private int rollNo;
    private double marks;

    public String getName() {
        // validation
        return name;
    }

    public void setName(String name) {
        // validation
        this.name = name;
    }

    public int getRollNo() {
        // validation
        return rollNo;
    }

    public void setRollNo(int rollNo) {
        // validation
        this.rollNo = rollNo;
    }

    public double getMarks() {
        // validation
        return marks;
    }

    public void setMarks(double marks) {
        // validation
        this.marks = marks;
    }
}

In the above example, all the data members are declared private so, no one can access these data members directly outside the class; for accessing these data members getter and setter methods are defined, inside these methods we can perform validation according to our requirements.

Leave a Comment