The access specifiers specifies accessibility (scope) of a data member, method, constructor or class.
There are 4 types of access specifiers:
- private
- default
- protected
- public
Example:
package date;
class Test {
private int number = 10;
private void display() {
System.out.println("Private Demo");
}
}
public class Demo {
/**
* @param args
*/
public static void main(String[] args) {
Test obj = new Test();
System.out.println(obj.number); // error occurs i.e. the field Test.number is not visible.
obj.display(); // error occurs i.e. The method display() from the type Test is not visible.
}
}
Default: If you don't use any modifier, it is treated as default by default. The default modifier is accessible only within package.
Example:
Class 1:
package date;
public class Demo {
/**
* @param args
*/
int number = 10;
void display() {
System.out.println("Private Demo");
}
public static void main(String[] args) {
}
}
Class 2:
package test;
import date.Demo;
public class demo {
/**
* @param args
*/
public static void main(String[] args) {
Demo obj = new Demo();
System.out.println(obj.number); // The field Demo.number is not visible
obj.display(); //The method display() from the type Demo is not visible
}
}
Example:
Class 1:
package date;
public class Demo {
/**
* @param args
*/
protected int number = 10;
protected void display() {
System.out.println("Private Demo");
}
public static void main(String[] args) {
}
}
Class 2:
package test;
import date.Demo;
public class demo extends Demo{
/**
* @param args
*/
public static void main(String[] args) {
demo obj = new demo();
System.out.println(obj.number);
obj.display();
}
}
Public: The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.
Example:
Class 1:
package date;
public class Demo {
/**
* @param args
*/
public int number = 10;
public void display() {
System.out.println("Private Demo");
}
public static void main(String[] args) {
}
}
Class 2:
package test;
import date.Demo;
public class demo {
/**
* @param args
*/
public static void main(String[] args) {
Demo obj = new Demo();
System.out.println(obj.number);
obj.display();
}
}
No comments:
Post a Comment