In: Computer Science
In JAVA, Explain how classes properly handle data hiding and implementation hiding
In java Object Oriented Features,Encapsulation is the methodology which ensures data hiding and implementation hiding.That means provides all the functionality for the data and its association but no one in the outer world will be able to see the inner construction and appliance of it.
Encapsulation mechanism in java wraps the data variables and the function acting on the data or methods in a single unit.We can hide the variables and the codes of that particular class from other class and outer world and also these data and method features will be unable to access by the inherited classes if we declare the variables of the class.Though we can view and set the variables by setter and getter methods.
The below code will be helpful to understand the concept explained above :
public class Main
{
public static void main(String[] args)
{
//declaring class object
Test t=new Test("John Smith","USA",23,'M');
//calling the getter methods to view the datas
System.out.println("Name : "+t.getName());
System.out.println("Country : "+t.getCountry());
System.out.println("Age : "+t.getAge());
System.out.println("Gender : "+t.getGender());
//we can override by using setter methods
t.setName("John Cena");
System.out.println("Name : "+t.getName());
t.setCountry("Canada");
System.out.println("Country : "+t.getCountry());
t.setAge(45);
System.out.println("Age : "+t.getAge());
}
}
class Test
{
//declaring variables using private keyword to ensure encapsulation
private String Name,Country;
private char Gender;
private int Age;
//constructor of the class
Test(String Name,String Country,int Age,char Gender)
{
this.Name=Name;
this.Country=Country;
this.Age=Age;
this.Gender=Gender;
}
//as the variables are declared as privade
//it cannot be accessed outside the class
//it can be accessed oytside this class only by
//using setter and getter methods as shown below
public void setName(String Name)
{
this.Name=Name;
}
public String getName()
{
return this.Name;
}
public void setCountry(String Country)
{
this.Country=Country;
}
public String getCountry()
{
return this.Country;
}
public void setAge(int Age)
{
this.Age=Age;
}
public int getAge()
{
return this.Age;
}
public void setGender(char Gender)
{
this.Gender=Gender;
}
public char getGender()
{
return this.Gender;
}
}