Java public keyword

2025年2月22日 | 阅读 3 分钟

Java public 关键字是一个访问修饰符。它可以用于变量、方法、构造函数和类。它是最不具限制性的访问修饰符。

注意事项

  • public 访问修饰符在任何地方都是可访问的。因此,我们可以轻松地在类和包内外访问 public 成员。
  • 如果您覆盖了任何方法,被覆盖的方法(即在子类中声明的方法)不能更具限制性。因此,如果您为任何方法或变量分配了 public,则该方法或变量只能使用 public 访问修饰符被覆盖到子类。
  • 如果一个程序包含多个类,最多只能将一个类指定为 public。
  • 如果一个类包含一个 public 类,则程序的名称必须与 public 类的名称相同。

public 关键字的示例

示例 1

让我们看一个示例,以确定 public 变量和方法是否可以在类外访问。在这里,我们也尝试在类外创建构造函数的实例。

输出

Try to access a public variable outside the class
Try to access a public method outside the class
Try to create the instance of public constructor outside the class

示例 2

让我们看一个示例,以确定 public 变量和方法是否可以在包外访问。在这里,我们也尝试在包外创建构造函数的实例。

输出

Try to access a public variable outside the package
Try to access a public method outside the package
Try to create the instance of public constructor outside the package 

示例 3

让我们看一个示例,以确定 public 方法是否可以使用 public 访问修饰符覆盖到子类。

输出

Try to access the overridden method

示例 4

让我们看一个示例,以确定 public 方法是否可以使用 private 访问修饰符覆盖到子类。

输出

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	Cannot reduce the visibility of the inherited method from A

示例 5

让我们看一个示例,以确定 public 方法是否可以使用默认访问修饰符覆盖到子类。

输出

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	Cannot reduce the visibility of the inherited method from A

示例 6

让我们看一个示例,以确定 public 方法是否可以使用 protected 访问修饰符覆盖到子类。

输出

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	Cannot reduce the visibility of the inherited method from A
下一个主题Return-keyword-in-java