Java: Information Hiding

Information hiding is a key feature of Java. When declaring a variable or a method, it can be one of four types: private, protected, public, or default.


To specify the type, use one of the three keywords or none at all.

Consider the following examples:

// Default
int i = 0;

// public
public int i = 0;

Public: When you declare a variable public, it means that it can be accessed anywhere in the program. If you inherit from that class, you would have access to all of the public variables.

Private: When a variable is private, it cannot be seen anywhere except in the class in which it is instantiated. If you use a class, you will not be able to see any private data.

Protected: If a variable is protected, you only have package access. (This is useful when developing libs.) That means that you will only see the variable in the package in which it is instantiated and all its subclasses.

Default: Default package access is achieved when there is no specifier (private, public, or protected). Default package access means that the variable is available within the package in which it is created but not in the package subclasses. Basically, you can think of it as a private package.

When creating variables within a method, you can only specify one keyword (final). You cannot create public, private, protected, or even default variables. When you create an Object within a method, it is only available within the method in which it is created.

If you have any questions e-mail me at staykovmarin@gmail.com

– Marin

The Conversation

Follow the reactions below and share your own thoughts.

5 Responses to “Java: Information Hiding”

  1. December 31, 2009 at 11:02 am, Anonymous said:

    On a scale of 1 to 10, I give this page a -1. One would expect a page for “Java Information Hiding” to actually talk about Information Hiding; what it is and what its advantages and disadvantages are. Instead, all this page says is “Information hiding is a key feature of Java.” This page does manage to mention access modifiers and while access modifiers are certainly a part of information hiding this page fails miserable to actually tie access modifiers to the concept of Information Hiding making the mere mention of them, like the rest of this page, useless.

    Reply

  2. December 13, 2010 at 12:55 pm, Rajesh_seaways said:

    why we must have to use at least one argument in main method ?

    Reply

  3. January 25, 2011 at 9:48 am, Imuh_chel said:

    how to make a for loop

    Reply

  4. January 25, 2011 at 9:50 am, Imuh_chel said:

    how to make a for loop on java

    Reply

    • February 24, 2013 at 4:20 pm, learner said:

      its same as c++ ….
      for(initialization;declaration;increment)

      Reply

Leave a Reply