print
Advertisment
Advertisment

Data Hiding in java

data hiding is a powerful feature in java. we can make data more secure by data hiding in java. by using the private keywords we can achieve data hiding property. if we make any variable private then we can use that variable directly. by using methods only we can use it. if we want to set the values in that variable, then we can't set the value directly. we have to use the setter method and forgetting the value of that variable we can't get directly that value, we have to use the getter method for that.

Syntex for Data hiding in java

private datatype variablename ;

Example for Data Hiding in java

class DataHiding{
	private String name;
	public static void main(String[] args) {
		DataHiding obj = new DataHiding();
		obj.setName("Data hiding in java");
		System.out.println(obj.getName());
	}
	public void setName(String name){
		this.name = name;
	}
	public String getName(){
		return name;
	}
}

Output :

	
	
	Data hiding in java
	
Advertisment

program without Data Hiding in java

Example for Data Hiding

class DataHiding{
   String name;
   public static void main(String[] args) {
      DataHiding obj = new DataHiding();
      obj.name = "Data hiding in java";
      System.out.println(obj.name);
   }
}

Output :

	
	
	Data hiding in java
	

in the above program, we can see. we are not using any method for using the name variable but also the variable is not private so any other class can access it by using the object directly. when we are not given permission for using that data then we have to make variables private. it's recommended to make every variable private and make the setter and getter method use that.

Advertisment
Advertisment
arrow_upward