Skip to main content

Data Hiding in Java

Data Hiding in Java

Data Hiding is an aspect of Object Oriented Programming (OOP) that allows developers to protect private data and hide implementation details. In this tutorial we examine basic data hiding techniques in Java. We also provide illustrations.

Object Oriented Programming provides techniques for modeling entities in the 'real world'. It has been observed that humans relate to real world things as objects. Objects have two basic characteristics, which we will briefly discuss here. For better or worse, the OOP industry has come up with various descriptors for these characteristics:

  • Properties, data, information, variables and constants, etc.
  • Code, methods, messages, actions, logic, etc.

This list could be extended indefinitely and is not intended to be complete by any means. The concept of Data Hiding is primarily concerned with the first category of characteristics, which will be referred to here simply as as data.

The Difference between a Class User and a Class Developer

In Java, a class is a programmer-defined data type that contains data and code (refer to the two categories of characteristics listed above). The term user refers to software programmers and system designers who apply a class in a larger program. Note that this definition of the word user might be contrary to common parlance. We are not referring to the end-user of an application program. That definition is certainly valid, but not in this context.

We differentiate between the author of the Java class and the user of the Java class. Both are humans, both have extensive software development knowledge, and both understand OOP concepts. Conceptually, the primary difference between the two humans is that the class author has domain knowledge and the user may not. Domain knowledge is the understanding of a real-world entity in order to model it with a software object. All programming obligates some domain knowledge. For example, a human who knows how to build a telephone might have the domain knowledge necessary to devise a software model of a telephone. Domain knowledge is 'built-in' to a software class. A user, on the other hand, can gather some domain knowledge from an existing software class but may not possess sufficient knowledge to actually program that model.

Data Hiding Prevents Class Users from Seeing Implementation Details

Class users typically do not need to see the implementation details of classes they employ in their programs. Hiding the details actually increases productivity because class users are not required to read reams of source code that has already been debugged by programmers with domain knowledge. In a perfect world, class users refer to class documentation (JavaDocs for example) instead of browsing class source code to discern functionality.

Data Hiding shields implementation details from class users and provides a convenient platform for enforcing data integrity rules on the class developer side. We illustrate both concepts in the following source code.

package DataHiding;

 * This class illustrates basic data hiding concepts
 * @author nicomp
public class Person {
//  public - a violation of data hiding 'rules'
    public int height;

//  private - not visible outside the class
    private float weight;

//  Here are 'get' and 'set' methods for the
//    private variable declared above.    
    public float GetWeight() { return weight;}

    public float SetWeight(float weight){
        if (weight >= 0)
            this.weight = weight;
        return this.weight;

General Rules for Data Hiding

In general, all variables in a class should be private. Since these variables, by definition of being private, are not visible outside the class, the class developer is obligated to provide 'gatekeeper' methods to class users. Certainty some private variables will be intended for use inside the class, but those that are intended to be visible to class users must be supplemented with "get" and "set" methods that are themselves public.

Examples of 'get' and 'set' Methods

Data Hiding is realized by 'get' and 'set' methods that provide access to private variables in a class. Lines 12, 17, and 19 (all above) illustrate this technique for the variable called weight. The class developer declared weight as private and coded methods to allow class users to read and write the variable.

Data Hiding rules are violated in line 9 (above). The variable height has been declared to be public. Syntactically the code is proper, but data integrity may suffer in the long run. Class users may unknowingly (or knowingly) corrupt the data in application programs. One job of the class developer is to provide mechanisms to protect data stored in the class; that responsibility was not met.

Code Written by the Class User

The following code illustrates how the class user might make use of the class we introduced above. Line 16 violates data hiding rules by accessing the class data directly. Note that we are not blaming the class user in this case; the class developer did not provide 'get' and 'set' methods nor did he/she make any attempt to protect the variable by declaring it private. The class user has no option other than to directly reference the variable.

Lines 20 and 21 illustrate proper techniques for making use of 'get' and 'set' methods by the class user. The class developer has declared the weight variable as private (see code above) and also provided methods for indirectly reading and writing the variable. The method GetWeight() (see code above) allows the class user to obtain a copy of the current value of the private variable. The method SetWeight(float weight) allows the class user to store a new value in the private variable. Note that SetWeight also includes a tiny bit of data integrity logic. The class user is prevented from storing a negative value in the weight. Data integrity logic is a direct function of domain knowledge; the class developer must have it.

package DataHiding;

 * @author nicomp
public class Main {

     * @param args the command line arguments
    public static void main(String[] args) {
        Person dude = new Person();

//      This is correct syntax, but bad programming
        dude.height = 60;

//      Use the 'get' and 'set methods to 
//        access the weight property.
        System.out.println("Weight = " + dude.GetWeight());



Data Hiding in Java provides techniques for implementing data integrity logic and for enforcing domain knowledge rules in Java classes.


nicomp really (author) from Ohio, USA on May 29, 2013:

Encapsulation is the combining of code and date (properties and methods) into a single unit, an object. The data in an object may not be hidden: it could be public.

kamran wazir on May 29, 2013:

what is difference between data hiding and encapsulation ?

RAMAKRISHNA imm on December 17, 2012:

Scroll to Continue

its very gud explnation .very happy

nicomp really (author) from Ohio, USA on August 31, 2012:

Rohit : No, it's not. Data (properties) can be encapsulated but not hidden.

nicomp really (author) from Ohio, USA on August 31, 2012:

Rohit 67 minutes ago

Data hiding is also called Encapsuation , see (redacted)

Dr Funom Makama from Europe on June 16, 2012:

Brilliant.. Thanks for the share

nicomp really (author) from Ohio, USA on June 11, 2012:

@stas: method and variable names are not limited to starting with a lower case letter. That is a convention.

stas on June 11, 2012:

One should not be allowed posting tutorials on Java for method names like these. In Java method and variable names start with a lowercase letter.

nicomp really (author) from Ohio, USA on June 11, 2012:

@Akshunya Vijay: Indeed!

Akshunya Vijay on June 10, 2012:

hat the hell are you sayingman the ibfo given by the author is almost perfect,the details given about name hiding and classes is the way it should have been ,thanks a lot respected author

nicomp really (author) from Ohio, USA on February 11, 2010:

@drbj: No worries. Thanks for the shout out!

drbj and sherry from south Florida on February 11, 2010:

I know this is a serious hub, nicomp, with tons of serious information but I'm still laughing at the acronym, OOP. Sorry. Wanted to give you a heads-up that I just wrote a new hub about choosing avatars and linked to you using your avatar as an example. 'Twas my pleasure and you can feel free to reciprocate any time.

Related Articles