How to Hide Data in Java
- 1). Load the NetBeans IDE by clicking on its program icon. When the program loads, navigate to "New/New Project" and select "Java Application" from the list on the right-hand side of the screen. A new source code file appears in the NetBeans text editor. The source code file contains a new class declaration and an empty main function. It should look something like this:
public Class className
{ public static int main(String[] args) {} } - 2). Create a hidden, or private, data member within the curly brackets of the class declaration but above the main method declaration. The private data member will be inaccessible except by special getter and setter methods. To every other object, the data member will be invisible. This is possible due to the use of the word "private" in the data member's declaration. Write the following between the curly brackets of the main method:
private int x = 4; - 3). Create a setter function named "setX" that will change the value of the variable x. The variable x cannot be changed in any other way because of its private attribute. It is effectively invisible to other objects. A setter function simply sets a value to variable x. Write the following below the statement written in the previous step:
public void setX(int y)
{ x = y; } - 4). Create a getter functions named "getX," which grabs the current value of x. This is the only way to find out what the value of x is, since it is private and accessible only from within this class. Write the following getter below the setter written in the previous step:
public int getX()
{ return x; } - 5). Create a new instance of this class using the main method. This allows you to access the getters and setters. To create a new instance of the class, write the following statement within the curly brackets of the main method:
className cN = new className (); - 6). Set the value of variable x using the setter function "setX." This is the only way to access this private field, since it is effectively invisible. Write the following statement below the previous statement, still within the curly brackets of the main method:
cN.setX(8); - 7). Get the value of variable x using the getter function "getX." This function can be used in conjunction with a print function to output the value to the output console. To print the value of x out to the console, write the following statement below the one written in the previous step:
System.out.println(cN.getX()); - 8). Run your program by pressing F6. The program hides variable x from everything but its own class, which has a getter and a setter method. By invoking these methods, you can set and get values for x without ever seeing x itself. The program prints out the value "8," since that was what x was changed to by the setter method.
Source...