How to Implement Data hiding in Java


Data Hiding is one of the important aspect of Object Oriented Programming (OOP) that enables developers to protect their private data and also hide implementation details from outside interference. In this tutorial we will try to learn basic data hiding techniques in Java by implementing a simple program.

Data Hiding in Java
package DataHidingInJava; /** * This class demonstrates simple data hiding concepts * @author solutionfactory.in */ public class Person { // public - keeping a variable public is a violation of data hiding 'rules' public float height; // private - This is not visible outside the class, hence hides the data private float weight; // Here are 'get' and 'set' methods for the // private variable declared above. // 'get' and 'set' methods are also called 'getters' and 'setters' respectively public float GetWeight() { return weight; } public float SetWeight(float weight){ if (weight >= 0) this.weight = weight; return this.weight; } }

Some Rules for Data Hiding

To implement data hiding, all the variables in a class should have private access modifier. Certain private variables are used outside the class and hence should be accessible in some way, so it is necessary to have public 'get' and 'set' method for those private variables.

Example of Using the variables from outside the class

package DataHidingInJava; /** * * @author solutionfactory.in */ public class Main { public static void main(String[] args) { Person p = new Person(); // This syntax is correct and will work as variable is public, but bad programming p.height = 60; // Use the 'get' and 'set methods to // access the weight variable // this is good programming skill that uses data hiding concept p.SetWeight((float)100.99); System.out.println("Weight = " + p.GetWeight()); } }

Conclusion

Data Hiding in java helps you to protect your data from outside interference and provides data integrity logic.

Solution Worked 6 UpvotesUpvote
        
Solution Didn't Worked 0 DownvotesDownvote


Comments




Search