Program without and with data hiding in java

280 Views Asked by At

I have studied data hiding in java theoretically but don't know what is happening inside. Every tutorial, states that unauthorized persons cant access the data of others.

Can anyone please give an example of what will happen without and with data hiding with two or three users programmatically?

1

There are 1 best solutions below

0
On

Data Hiding is hiding internal data from outside users. This is achieved by making the attributes of your class private and not letting the objects of the class access it directly, instead we create getters and setters to access the private attributes. Example:

//Without Data Hiding

public class Model{
public String name;
}

public class JavaApp{
public static void main(String args[]){
Model mObj = new Model();
mObj.name="abc";     // name = "abc"

}
}

//With Data Hiding

public class Model{
private String name;   //private name
}

public class JavaApp{
public static void main(String args[]){
Model mObj = new Model();
mObj.name="abc";     // Error
}
}