Saturday 2 March 2013

Access Modifiers/Control


Java provides four types of Access Modifiers.  They are public, protected, default and private.

Access Location
public
protected
friendly or default
private
Same class
Y
Y
Y
Y
Sub class in same package
Y
Y
Y
N
Other classes in same package
Y
Y
Y
Y
Sub classes in other packages
Y
Y
N
N
Non-sub classes in other packages
Y
N
N
N


For good programming technique place member data as private and member functions as public.


Example:

class modi
{
            private int k=6;
            void display()
            {
            System.out.println("k in display="+k);
            }
}
class ex
{
            public static void main(String[] args)
            {
            modi obj=new modi();
            obj.display();
            //System.out.println("k in main="+obj.k);
            //this statement provides error since private variable
            //can not be possible to access by other class
            }
}

No comments:

Post a Comment