Software & Finance





Java - Data Hiding





Data Hiding is a concept in Java. We got the luxary of hiding data using e different access levels - private, protected, public using Java Programming Language.

Private members and functions can only be accessed by class members of the class. You can think the data abstraction is also using data hiding techniques. Protected members can be accessed only by the class and its derived classes.

 

In this sample code, the class CStudent members variables such as name, age, addr1, etc can not be accessed directly. You need to go through the interfaces functions to access these members.

 

 

Source Code


import java.io.*;

import java.lang.*;

import java.util.*;

import java.text.*;

 

class CStudent

{

      private String name;

      private int age;

      private String addr1;

      private String addr2;

      private String city;

      private String zipcode;

 

      public CStudent() { }

 

      public String GetName() { return name; }

      public String GetAddr1() { return addr1; }

      public String GetAddr2() { return addr2; }

      public String GetCity() { return city; }

      public String GetZipCode() { return zipcode; }

      public int GetAge() { return age; }

 

      public void SetName(String s) { name = s; }

      public void SetAddr1(String s) { addr1 = s; }

      public void SetAddr2(String s) { addr2 = s; }

      public void SetCity(String s) { city = s; }

      public void SetZipCode(String s) { zipcode = s; }

      public void GetAge(int v) { age = v; }

};

 

class DataHiding

{

      static public void main(String[] args)

      {

            CStudent s = new CStudent();

 

            // s.name = "softwareandfinance.com"; // Not allowed, compiler error name has private access in CStudent

            // System.out.print(s.name);

 

            s.SetName("softwareandfinance.com");

            System.out.print(s.GetName());           

      }

}

Output


D:\Program Files\Java\jdk1.6.0_23\bin>javac DataHiding.java

 

D:\Program Files\Java\jdk1.6.0_23\bin>java DataHiding

softwareandfinance.com