How many access modifier are their in
java ?
There
are 4 access modifiers
a)
public - can be accessed from any Class outside or inside of the
same package.
b)
protected - can be accessed from inside the same package and
outside of the
other package in subclasses.
c)
default or no access modifier – can be accessed from the inside of
the package
d)
private – can be accessed from the same class.
These
4 modifiers are applied to non-local variables and methods only.
There
are only 2 modifiers which can be applied for Class declaration
(default and public)
For
better understanding, member level access is formulated as a table:
| Access Modifiers | Same class | Same package | Same package subclass | other package subclass | other package non subclass |
|---|---|---|---|---|---|
| public | Yes | Yes | Yes | Yes | Yes |
| protected | Yes | Yes | Yes | Yes | No |
| default | Yes | Yes | Yes | No | No |
| private | Yes | No | No | No | No |
In the code below access modifiers are in red colour.
package com.fastlearned;
public class AccessModifierTest {
public String pub_string = "public string";
protected String pro_string = "protected string";
String de_string = "default string";
private String pri_string = "private string";
/*
* This is a public method which can be called from anywhere
*/
public void testPublicMethod()
{
System.out.println("Test public method ");
}
/*
* This is a protected method which can be called from
* anywhere in this package or from a subclass of this class
* outside the package
*/
protected void testProtectedMethod()
{
System.out.println("Test protected method ");
}
/*
* This is a default method which can be called from
* anywhere in this package
*/
void testDefaultMethod()
{
System.out.println("Test default method ");
}
/*
* This is a private method which can be called from
* this class only
*/
private void testPrivateMethod()
{
System.out.println("Test private method ");
}
}
No comments:
Post a Comment