Java provides four types Access
modifiers as public, private, default and protected. Any variable declared as public, it could be
accessed from anywhere. Any variable
declared as private cannot be seen outside of its class. Any variable declared as default, it is
visible to subclasses as well as to other classes in the same package. Any variable declared as protected, it allows
an element to be seen outside of current package, but only to classes that
subclass directly.
|
public
|
private
|
default
|
protected
|
Same class
|
Yes
|
Yes
|
Yes
|
Yes
|
Same package sub class
|
Yes
|
No
|
Yes
|
Yes
|
Same package non-subclass
|
Yes
|
No
|
Yes
|
Yes
|
Different package sub class
|
Yes
|
No
|
No
|
Yes
|
Different package non-subclass
|
Yes
|
No
|
No
|
No
|
Example:
package p1;
public class protect
{
int
n=1;
private
int n_pri=2;
protected
int n_pro=3;
public
int n_pub=4;
public
protect()
{
System.out.println("Super
constructor");
System.out.println("default="+n);
System.out.println("private="+n_pri);
System.out.println("protected="+n_pro);
System.out.println("pubic="+n_pub);
}
}
package p1;
class derive extends protect
{
derive()
{
System.out.println("Sub
constructor");
System.out.println("default="+n);
//System.out.println("private="+n_pri);
//since
it is a private variable in package p1
System.out.println("protected="+n_pro);
System.out.println("pubic="+n_pub);
}
}
import p1.protect;
class same
{
public
static void main(String[] args)
{
protect
obj=new protect();
}
}
No comments:
Post a Comment