Java Access Modifiers

Questions to be answered:

  1. What are access modifiers and why do we need them in Java?
  2. What are the class-level and method-level access modifiers and its visibility?

Access modifiers assists in maintaining the Encapsulation property of Object Oriented Programming concept. For now, just assume that Public means accessible by anyone who has a copy of the class.

Also Read:

public class AccessMod {

          public String password;

          public void setPassword(String passwd) {
               password = passwd;
          }

          public String getPassword() {
               return password;
          }
}

Can you spot the problem in this code? Think about it for a minute. Yes. You are right, there is a security risk that someone who creates an object of this class can misuse the class instance variable “password” as he likes because the access modifier is Public. The objective of this programmer is to allow only the two methods to be invoked by end user but has ended up allowing too much access to client.

Is this desirable? No. We need some mechanism to prevent such variables from being accessed by the outside world. To encounter such problems, Java has a mechanism called “Access Modifiers” wherein it allows clients to restrict visibility to the end user based on the needs.

Java has two types of access level modifiers:

  1. Class level modifiers – public and Default. Only inner classes can be declared as private.
  2. Method/Variable level modifiers – public, private, protected and Default.

Note: There is no such keyword as Default. It is being used just for illustration.

Public

As the name indicates, any class/method/variable declared as public can be accessed by anyone.

public class PublicMod {

     public String keyword;

     public void setKeyword(String keywd) {
          keyword = keywd;
     }

     public String getKeyword() {
          return keyword;
     }
}

Client Program:

public class ClientProgram {
    public static void main (String args[]) {
          PublicMod mod = new PublicMod();
          mod.keyword = "public";
          mod.setKeyword("yahoo");
          mod.getKeyword();
    }
}

As it can be seen, all variables/methods declared as Public can be accessed from the client program without any issues. Now you know the reason why main() method is declared as public. So that it can be invoked by JVM.

Private

An instance variable/method/inner class having private access modifier can only be accessed within its own class.

public class PrivateMod {

     private String keyword;

     public void setKeyword(String keywd) {
          keyword = keywd;
     }

     public String getKeyword() {
          return keyword;
     }

     private class PrivateClass() {
          /* Only inner classes may be declared as private */
     }

}

The only difference from previous example is the use of Private instance variable. What’s the difference you may ask? The difference lies in the way client program accesses the data.

public class ClientProgram {

          public static void main(String[] args) {
               PrivateMod mod = new PrivateMod();

               /* This line will give an error because in the class this field has been declared as private and so can't be accessed by anybody outside its own class */

               mod.keyword = "private"; // see above
               mod.setKeyword("working");
               mod.getKeyword();

          }
}

So by declaring the variable to have private modifier, we are able to hide this data from the end user, thereby not allowing him to modify it without our permission. Next question you may think about is why only the inner classes may be declared as private? Think about it for a second.

Assume you declare a class as Private. Will you be able to access it outside the class? No, never. Why? Because its private only within the class. What’s the use of a private class if no end user can use it. That’s the reason Java allows only private inner classes inside a public class as the end user can still access the public class but not its inner private class.

Protected

This access modifier is mostly used in Inheritance, which is again an Object Oriented Programming concept. By declaring a variable/method to be protected, Java allows access to only sub classes and all classes within the same package and outside package.

package class.org;

public class ProtectedMod {

          protected String keyword;

          protected void setKeyword(String keywd) {
               keyword = keywd;
          }

          protected String getKeyword() {
               return keyword;
          }
}

So these protected variables/methods can only be invoked by sub classes, which extend these classes and all classes within the class.org package. Now on to the default modifier, which can be quite tricky in its name.

Default / No modifier

We never declare any variable/class/method using Default modifier. If we forget to use any of public/private/protected modifiers, then it is considered to be default modifier. A class/method without any modifiers can only be accessed by classes within that particular package.

package default.mod;

class DefaultMod {

          String keyword;

          void setKeyword(String keywd) {
               keyword = keywd;
          }

          String getKeyword() {
               return keyword;
          }
}

package default.mod;

public class ClientProgram {

          public static void main (String args[]) {
                DefaultMod = new DefaultMod();
                mod.keyword = "default";
                mod.setKeyword("Thanks");
                mod.getKeyword();
          }
}

The class DefaultMod and its default variables/methods can only be accessed by classes within the package.

Summary

We have come to the end of the tutorial on access modifiers. In short, access modifiers helps us provide visibility to classes/methods/variables in Java according to our needs. Hope you found this post useful. If you have any questions/comments, feel free to post them in the “Comments” section.

This article is originally published at Java tutorials – Lets jump into the ocean, re-posted here with authors permission and as part of the JBC program.

Comments

comments

About Rengasudharsan Srinivasan

Renga is currently working as a software engineer. He has experience developing web applications using spring, struts and Hibernate framework. He is passionate about learning new technologies and has recently started writing a blog http://renga86.blogspot.com mainly focussing on Java.

Speak Your Mind

*