Private: 私有修饰符的访问级别仅在该类之内。不能从班级外部访问它。
Default: 默认修饰符的访问级别仅在包中。不能从软件包外部访问它。如果您未指定任何访问级别,它将是默认级别。
Protected: 受保护的修饰符的访问级别通过子类在程序包内和程序包外。如果您不创建子类,则无法从包外部对其进行访问。
Public: 公共修改器的访问级别无处不在。可以从类内部,类外部,包内部和包外部对其进行访问。
访问修饰符 | class中 | package中 | 子类package外 | package外 |
Private | Y | N | N | N |
Default | Y | Y | N | N |
Protected | Y | Y | Y | N |
Public | Y | Y | Y | Y |
class A{
private int data=40;
private void msg(){
System.out.println("Hello java");
}
}
public class Simple{
public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);
//Compile Time Error obj.msg();
//Compile Time Error }
}
class A{
private A(){
}
//private constructorvoid msg(){
System.out.println("Hello java");
}
}
public class Simple{
public static void main(String args[]){
A obj=new A();
//Compile Time Error }
}
//save by A.javapackage pack;
class A{
void msg(){
System.out.println("Hello");
}
}
//save by B.javapackage mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
//Compile Time Error obj.msg();
//Compile Time Error }
}
//save by A.javapackage pack;
public class A{
protected void msg(){
System.out.println("Hello");
}
}
//save by B.javapackage mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Output:Hello
//save by A.javapackage pack;
public class A{
public void msg(){
System.out.println("Hello");
}
}
//save by B.javapackage mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
class A{
protected void msg(){
System.out.println("Hello java");
}
}
public class Simple extends A{
void msg(){
System.out.println("Hello java");
}
//C.T.Error public static void main(String args[]){
Simple obj=new Simple();
obj.msg();
}
}