1.

Scope of Access Specifiers in Java

Answer»

A Java access specifier shows the capability to specific classes to access a given class and its components. They are also called access modifiers. They help limit the scope of the class, constructor, variables and methods.

Basically, there are four access specifiers in Java

  • Default (No keyword required)
  • Public
  • Private
  • Protected

The FOLLOWING table illustrates the visibility of the access specifiers

Access Specifiersdefaultprivatepublicprotected
Accessible WITHIN same classYesYesYesYes
Accessible to other classes in same packageYesNoYesYes
Accessible within the SUBCLASS inside the same packageYesNoYesYes
Accessible within the subclass outside the packageNoNoYesYes
Accessible to other non subclasses outside the packageNoNoYesNo

Let us see an example:

class Scope {    private int x=5;         // a private variable can only be accessed in the same class    protected int k=10;  // a protected variable can be accessed in the subclass    public void print()    // a public method which can be accessed anywhere    {        System.out.println(x);    } } public class Example extends Scope {    public STATIC void main(String[] args)    {        Scope s=new Scope();        s.print();        System.out.println(s.k);    } }

The program gives the following output:

$javac Example.java $java Example 5 10


Discussion

No Comment Found