Access specifiers
Access specifiers are used to declare that who can access the method and data members of a class .We have seen many programs till now and often keyword pubic was used .By using this keyword we declared the class or method to be public.
We have Four types of Access Specifiers :
- public
- protected
- default
- private
public :
If a class or method is public , it means the method can be accessed in the same class , as well as in other class in same package and in the class of other packages as well . Also can be accessed by the derived classes
protected :
If a method or class is protected , it means that the method can be accessed by the classes of that package only to which the class itself belongs . And methods can be accessed by derived class can also be accessed .
If the class belongs to some other package and is not a derived class , it cannot access the methods of protected class .
default :
If we do not declare any access specifier , default case is considered . In this the method can be accessed by all the classes of that package to which the class itself belongs . Classes which belong to other package strictly cannot access the methods of default class in any condition.
private :
Methods of a private class can be accessed only in that class. Even classes of same package or derived classes cannot access the methods of private class.
For better understanding , refer to the following example:
Let classes c1,c2,c3 belong to same package A. And classes c4 and c5 belong to another package B.
Also assume that class c4 is inherited from class c1.
Now we consider class c1 , in this class let we have some methods .
If the we declare the class as public then the methods of this class can be accessed by class c1 , c2, c3 ,c4 as well as c5. that is all types of classes can access the methods of a public class .
If we declare the class c1 as protected , methods of class c1 can be accessed by c1, c2 ,c3 as well as c4 .Note that class c5 wont be able to access the methods of protected class c5 as it does not belong to same package . Note that class c4 is also not of same package but is inherited from class c1. Hence we come to conclusion that in case of protected class , the methods can be accessed by same package as the class belongs to or by the derived classes of that class .
If we declare the class c1 as default class , then the methods of class c1 can be accessed by class c1,c2 and c3 only . Classes c4 and c5 wont be able to access the methods of class c1 as they do not belong to same package as the class c1 belongs to . In default, kit dosnt matter if the class is inherited by some other class of some other package .
If we declare the class c1 as private , then the methods of class c1 can be accessed only in class c1 . Classes of same package wont be able to access the methods of c1 here . Inherited classes are also not allowed to access the methods of a private class.
0 comments:
Post a Comment