每当我们编写我们的类时,我们必须向 JVM 提供一些关于我们的类的信息,比如这个类是否可以从任何地方访问,是否可以创建子类,是否可以创建对象等等。我们可以通过在Java称为访问修饰符的适当关键字来指定此信息。因此访问修饰符用于设置类、方法和其他成员的可访问性。
公共访问修饰符:
如果一个类被声明为公共类,那么我们可以从任何地方访问该类。
在下面的示例中,我们在该包中创建了一个包 pack1,我们声明了一个公开的类 A,在该类中,我们声明了一个也是公开的方法 m1。现在我们创建另一个包 pack2 并在该包中导入 pack1 并声明一个类 B,在类 B 的 main 方法中,我们创建一个类 A 类型的对象并尝试访问方法 m1 的数据。
Java
// Java program to showcase the example
// of public access modifier
// import required packages
import java.io.*;
import java.util.*;
// declaring a public class
public class A {
// declaring method m1
public void m1() { System.out.println("GFG"); }
}
class B {
// main method
public static void main(String[] args)
{
// creating an object of type class A
A a = new A();
// accessing the method m1()
a.m1();
}
}
Java
// Java program to showcase the example
// of private access modifier
// import required packages
import java.io.*;
import java.util.*;
// helper class
class A {
// helper method
private void m1() { System.out.println("GFG"); }
}
// driver class
class B {
// main method
public static void main(String[] args)
{
// creating an object of type class A
A a = new A();
// accessing the method m1()
a.m1();
}
}
输出
GFG
如果在编译 B 类时 A 类不是公共的,我们将收到编译时错误,提示 pack1。 A 在 pack1 中不是公共的,不能从外部包访问。
类似地,如果一个成员或方法或接口被声明为 public,那么我们可以从任何地方访问该成员。
私有访问修饰符:
此修饰符不适用于顶级类或接口。它仅适用于类中的构造函数、方法和字段。
如果变量或方法或构造函数被声明为私有,那么我们只能从类内部访问它们,即从类外部我们无法访问它们。
Java
// Java program to showcase the example
// of private access modifier
// import required packages
import java.io.*;
import java.util.*;
// helper class
class A {
// helper method
private void m1() { System.out.println("GFG"); }
}
// driver class
class B {
// main method
public static void main(String[] args)
{
// creating an object of type class A
A a = new A();
// accessing the method m1()
a.m1();
}
}
Public Access Modifier | Private Access Modifier |
---|---|
This modifier is applicable for both top-level classes and interfaces. | This modifier is not applicable for both top-level classes and interfaces. |
Public members can be accessed from the child class of the same package. | Private members cannot be accessed from the child class of the same package. |
Public member can be accessed from non-child class of same package. | Private members cannot be accessed from non-child class of same package. |
Public members can be accessed from child class of outside package. | Private members cannot be accessed from child class of outside package. |
Public members can be accessed from non-child class of outside package. | Private members cannot be accessed from non-child class of outside package. |
Public modifier is the most accessible modifier. | Private modifier is the most restricted modifier. |
Public modifier is the recommended modifier for method. | Private modifier is the recommended modifier for data members. |