Wednesday, August 24, 2011

Java Access Modifier

While waiting for the lunch time lets do something very basic but quiet interesting; Java access modifier.

There are four access modifiers in Java: public, protected, private, and package access. Suppose we have a project with package structure as below:



There are four classes:
1. A superclass for other classes named SuperClass
2. A subclass of class SuperClass named SubClassA which resides at the same package as its superclass.
3. A subclass of class SuperClass named SubClassB which resides at different package as its superclass.
4. Another class at different package named Main.



The SuperClass has all four different level access method. We will see which methods are visible at any of the other three classes.



We can see that the public, protected, and package access level methods are visible in class SubClassA through both inheritance and reference.



Now we can see that there are only public and protected methods visible to class SubClassB through inheritance and only public method visible through reference. This happens because package level access, as its name suggest, only applies for classes reside at same package. Whereas protected applies for all of its subclasses.

There is a note here regarding overriding protected method. As we can see in class SubClassB, we override method protectedMethod from its superclass. Therefore, all classes at the same package with class SubClassB can access SubClassB's protectedMethod through reference. However, if we didn't override the protectedMethod, all other classes at the same package wouldn't be able to access it at all because protectedMethod would become private in SubClassB.



For a class at another package, as we can see in class Main, can only access public methods.

The access levels are simple and clear, aren't they? All method modifiers also apply to instance variables as well. OK, now it's time to go out for lunch.

0 comments:

 

©2009 Stay the Same | by TNB