Previous | Home | Next |
Access modifiers determines the accessibility scope of the Java elements that are being modified. If we not explicitly use an access modifier with a Java element, the element implicitly has the default access modifier.
The explicit access modifiers may be used with a class and its members. They cannot be used with the variables inside a method. The Java has three explicit access modifiers viz. public, private and protected, and also has a default modifier, which is used when you do not explicitly specify a modifier.
The public modifier makes an element most visible, it can be applied to various classes and their members (instance variable and methods). The elements declared public can be accessed from anywhere in the java application. That is why you declare the main method of any application public so that it may be invoked from any Java runtime environment. The syntax for declaring and using public modifiers within java program can be shown as:
Example
Java Tutorialslass ModifierDemo { public int i; public ModifierDemo(int i) { this.i=i; System.out.println("the value of i is :"+i); } } [an error occurred while processing this directive] Java Tutorialslass PublicModifier { public static void main(String[] args) { ModifierDemo obj=new ModifierDemo(10); } }
The private modifier is used to make a java element least visible. The private modifier cannot be used for a top-level class, and can be applied only to the members of a top-level class viz. instance variables, methods. A private member of a class can only be accessed from the code inside the same class in which this member is declared. It cannot be accessed from any other class or from a subclass of the class in which it is declared.The code snippet shows the syntax for using private modifier.
Example
Java Tutorialslass ModifierDemo { private int i=10; public int j=5; } Java Tutorialslass PublicModifier { public static void main(String[] args) { ModifierDemo obj=new ModifierDemo(); System.out.println("The value of i is :"+obj.i); // cause a compile error as i's defined private. System.out.println("The value of j is :"+obj.j); // print the value of j =5 } }
The accessibility of i have been kept private so we can't directly access it merely by creating the object of the class in which it is defined, so it will cause a compiler error, but if we comment out this line from prog. then we will get the value of j=5 as output.
Previous | Home | Next |