MY mENU


Wednesday 9 January 2013

Access Modifiers in Java

The keywords which define accessibility permissions are called accessibility modifiers. Java supports four accessibility modifiers to define accessibility permissions at different levels.  In java, we have below 4 accessibility levels
1. Only within the class
2. Only within the package
3. Outside the package but only in subclass
4. From all places

Accessibility modifier keywords: To define the above four levels we have 3 key words.

  1.  Private: the class members which have private keyword in its creation statement are called private members. Those members are only accessible with in that class. 
  2. Protected: the class members which have protected keyword in its creation statements are called protected members. Those members can be accessible with in package from all classes, but from outside package only in subclass that too only by using subclass name or its object. 
  3. Public: the class and its member which have public keyword in its creation statement are called public members. Those members can be accessible from all places of java application. 
In class or its member’s declaration if we do not use any of the above 3 accessibility modifiers, the default accessibility level is package.
  • Default and public are the accessibility modifiers allowed for a class. 
  •  4 accessibility modifiers are allowed for class members. 
  • The default accessibility modifier of interface is package level and its member’s default accessibility is public.
Example:
class AccessModifierEx 
{
private static int a=10;
static int b=20;
protected static int c=30;
public static int d=40;

public static void main(String[] args) 
{
System.out.println("a="+a);
System.out.println("b="+b);
System.out.println("c="+c);
System.out.println("d="+d);
}
}

No comments:

Post a Comment