Introducing Access Control

By: aathishankaran Emailed: 1766 times Printed: 2515 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

             As you know, encapsulation links data with the code that manipulates it. However, encapsulation provides another important attribute: access control. Through encapsulation, you can control what parts of a program can access the members of a class. By controlling access, you can prevent misuse. For example, allowing access to data only through a well-defined set of methods, you can prevent the misuse of that data. Thus, when correctly implemented, a class creates a “black box” which may be used, but the inner workings of which are not open to tampering. However, the classes that were presented earlier do not completely meet this goal. For example, consider the Stack class shown at the end of the Recursion article. While it is true that the methods push() and pop() do provide a controlled interface to the stack, this interface is not enforced. That is, it is possible for another part of the program to bypass these methods and access the stack directly. Of course, in the wrong hands, this could lead to trouble. In this section you will be introduced to the mechanism by which you can precisely control access to the various members of a class.

             The access specifier that modifies its declaration determines how a member can be accessed. Java supplies a rich set of access specifiers. Some aspects of access control are related mostly to inheritance or packages. (A package is, essentially, a grouping of classes.) These parts of java’s access control mechanism will be discussed later. Here, let’s begin by examining access control as it applies to a single class. Once you understand the fundamentals of access control, the rest will be easy.

             Java’s access specifiers are public, private, and protected.  Java also defines a default access level. protected applies only when inheritance is involved. The other access specifiers are described next.

             Let’s begin by defining public and private. When a member of a class is modified by the public specifier, then that member can be accessed by any other code in your program. When a member of a class is specified as private, then that member can only be accessed by other members of its class. Now you can understand why main() has always been preceded by the public specifier. It is called by code that is outside the program that is, by the java run-time system. When no access specifier is used, then by default the member of a class is public within its own package, but cannot be accessed outside of its package.

             In the classes developed so far, all members of a class have used the default access mode, which is essentially public. However, this is not what you will typically want to be the case. Usually, you will want to restrict access to the data members of a class allowing access only through methods. Also, there will be times when you will want to define methods, which are private to a class.

             An access specifier precedes the rest of a member’s type specification. That is, it must begin a member’s declaration statement. Here is an example:

                public int i;

        private double j;

        private int myMethod(int a, char b) {//…

To understand the effects of public and private access, consider the following program:

class Test {

     int a;

     public int b;

     private int c;

      void setc(int i) {

          c = i;

     }

     int getc() {

          return c;

     }

}

class AccessTest {

     public static void main(String args[]) {

          Test ob = new Test ();

          ob.a = 10;

          ob.b = 20;

          ob.setc(100);

          System.out.println(“a, b, and c: “ + ob.a + ”  “ + ob.b+ “  “+ ob.getc());

     }

}

            As you can see, inside the Test class, a uses default access, which for this example is the same as specifying public. b is explicitly specified as public. Member c is given private access. This means that it cannot be accessed by code outside of its class. So, inside the AccessTest class, c cannot be used directly. It must be accessed through its public methods: setc() and getc(). If you were to remove the comment symbol from the beginning of the following line;

            ob.c = 100;

then you would not be able to compile this program because of the access violation.

            To see how access control can be applied to a more practical example, consider the following improved version of the Stack class shown at the end of the article Recursion.

class Stack {

     private int stck[] = new int [10];

     private int tos;

Stack() {

     tos = -1;

}

void push(int item) {

     if( tos==9)

          System.out.println(“Stack is full.”);

     else

          stck[++tos] = item;

}

int pop() {

     if(tos <0) {

          System.out.println(“Stack underflow.”);

          Return 0;

     }

     else

         return stck[tos--];

     }

}

As you can see, now both stck, which holds the stack, and tos, which is the index of the top of the stack, are specified as private. This means that they cannot be accessed or altered except through push() and pop(). Making tos private, for example, prevents other parts of your program from inadvertently setting it to a value that is beyond the end of the stck array.         


Java Home | All Java Tutorials | Latest Java Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(0)


Be the first one to add a comment

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by aathishankaran
Web Security Issues
The Web User's Perspective
Server-side plug-Ins
The best way to avoid security vulnerabilities with new server
JavaScript Security
Window Object
Working with Status Bar Messages
Retrieving a Portion of a String
Referencing Windows
Math Object
Frame Object
Document Object
Closing Windows
Built-in Object in Javascript
Textarea Object

More Tutorials in Java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Java File
Java String
Count number of vowels, consonants and digits in a String in Java
Reverse a number in Java
Student marks calculation program in Java
Handling Fractions in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java
Multiple Inheritance sample in Java
Java program using Method Overriding
Java program to check if user input is an even number

More Latest News
Most Viewed Articles (in Java )
A Serialization Example in Java
Type Casting in Java
instanceof sample program in Java
FilenameFilter - sample program in Java
Using One-Dimensional Arrays in Java
Method Overriding in Java
indexOf( ) and lastIndexOf( ) in Java
The java Buzzwords
Write to a file in Java - Sample Program
What is Java?
FileReader and FileWriter example program in Java
A Tutorial on importing packages in Java
How to use ArrayList in Java
Extract characters in Java
XML and Java - Parsing XML using Java Tutorial
Most Emailed Articles (in Java)
Converting a number into its equalant value in words in Java
java.lang.reflect package
Disadvantages of using Native methods in Java
What is UCS? What is ISO 10646?
Generating Your Key Pair example using keytool in Java
Operator Precedence in Java
PushbackReader sample program in Java
concat(), replace(), and trim() Strings in Java
instanceof sample program in Java
Use of - new - in Java
The Benefits of OOP
Increment and Decrement Operator
Characters in java
The continuing Revolution of java
Why java is important to the Internet