Sunday, October 17, 2010

What are Access specifiers in java with examples

Here is a table showing the effects of

access specifiers

for class members. “
Y---yes
blank---no

Specifierclasssubclasspackageworld
privateY


protectedYYY
publicYYYY
(none)Y
Y

If a variable is declared protected, then the class itself can access it, its subclass can access it, and any class in the same package can also access it, but otherwise a class cannot access it.
If a class memeber doesn't have any access specifier (the “none” row in above), its access level is sometimes known as “package”.
Here's a example.
class P {
    int x = 7;
}
public class AS {
    public static void main(String[] args) {
        P p = new P();
        System.out.println(p.x);
    }
}
The code compiles and runs. But, if you add “private” in front of “int x”, then you'll get a compiler error: “x has private access in P”. This is because when a member variable is private, it can only be accessed within that class.

Access specifiers for constructors:
 
Constructors can have the same access specifiers used for variables and methods. Their meaning is the same. For example, when a constructor has “private” declared, than, only the class itself can create a instance of it. (kind of like self-instance) Other class in the same package (file) can not create a instance of that class. Nor any subclass of that class. Nor any other class outside of this package (file).

Sample code.

          class Access1 
          {                                      
            public int x;
            private Access1(int n
             {           
                x=n;
                System.out.println("i'm born!");
              }
           }
      //anothet class begins                                            
       class Ass
        {   
        public static void main(String[] args) 
        {
           Access1  q = new Acess1(3);    
            System.out.println(q.x);
         }  
        } 
       }
  
In the above code, it won't compile because Access1`s constructor is “private” but it is being created outside of itself. If you delete the “private” keyword in front of Access1`s constructor, then it compiles.
Remember that a class can have more than one constructors, each with different parameters. The constructors needs not all have the same access specifier.
In the following example, the class Access1 has two constructors, one takes a int argument, the other takes a double argument. One is declared private, while the other with no access specifier (default package level access).

class Access2
  {
       Access2(int n) {
        System.out.println("i'm born int!");
    }
    private Access2(double d) {
        System.out.println("i'm born double!");
    }
}

public class ASS2 {
    public static void main(String[] args) { 
           Access2 q1 = new Access2(3);
        //Access2 q2 = new Access2(3.3);
    }
}

The fact that there can be constructors with different access specifiers means that in Java, the ability to create a object also depends on which constructor is called to create the object.

Access specifiers for classes:
                        For classes, only the “public” access specifier can be used on classes. Basically, Java has this “One Class Per File” paradigm. That is, in every java source code file, only one class in the file is public accessible, and that class must have the same name as the file. (For Example, if the file is “xyz.java”, then there must be a class named “xyz” in it, and that is the class that's public.) Optionally, the class can be declared with “public” keyword.
If you use any other access specifier on classes, or declare more than one class “public” in a file, the compiler will complain. For brief, see Packages in Java.


 

 






The complexity of access specifiers in OOP:

The rise of the elaborate access specifiers and their different consequences in Java entities is a complexity out of OOP and its machinery.
Note that the concept of access specifiers such as “private” is not at all related to issues of secrecy or the all-important aspect of cryptography in computing. Compiled Java code can relatively easily be decompiled by compiler specialists.
The concept of access specifiers is arisen out of the perceived need of good engineering practices. More specifically: to provide a way in the language of OOP paradigm to specify and control what items can not be accessed.
This concept and scheme, is not relevant to some 95% of programing in the real world. In writing Java code, one doesn't have to fret over them. Nothing's gonna happen if you declare everything public. Just about every other programing language are all “public” and babies are still born every second.
As we've seen above, these “access specifiers” has different meanings when used on different Java entities. When used on class variables or methods, they control where these variable/methods can not be used. When used on constructors, they control where a class can not be instantiated. And when applied to classes, they declare which class cannot be seen. How exactly did these complexities arise?
To find the answer, we realize that all these differences, including the concept of access specifiers, is a immediate consequence of OOP.Classes and methods are really just subroutines and inner-subroutines. And, a instance of a class (objects), are really just variables assigned with such super-subroutines as values. Naturally, when one deals with super-subroutines and execute commands by assigning them to variables and calling inner-subroutines through these variables, complexity ensues.
Normally, the scoping of variables can be classified as one of dynamic or lexical, or that of global and local. Now with OOP ways, a variable in a class has a scope, while the same variable when the class is instantiated (an object) is a different scoping issue. Also, the scope concept applicable to variables is now broadened to methods (inner-subroutines) and constructors (specialized inner-subroutines). All in all, the scoping complexities of OOP as applied to different OOP entities is manifested as access specifiers in Java.

No comments:

Post a Comment

Post a Comment