Home >Java >javaTutorial >Java function access permission modifier public usage guide
Java public access modifier allows functions to be accessed from anywhere and is used to declare public APIs, define tools and utilities that are shared across packages or classes. The specific usage is as follows: Syntax: public return value type function name (parameter list) { ... } Scenario: functions that need to be accessed from anywhere, methods in public APIs, shared tools or utilities
Java Function Access Permission Modifier Public Usage Guide
What is Public?
In Java, public
is an access modifier used to declare that a function can be accessed from anywhere, regardless of package or class restrictions.
Syntax
public 返回值类型 函数名称(参数列表) { // 函数体 }
Usage scenarios
public
Modifiers are usually used in the following scenarios:
Practical case
Scenario: Define a public function used to calculate the sum of two numbers.
Code:
public class SumUtil { // 公共函数用于计算两个数字之和 public int sum(int a, int b) { return a + b; } } **调用示例:**
public class Main {
public static void main(String[] args) { // 创建 SumUtil 实例 SumUtil sumUtil = new SumUtil(); // 调用公共函数 sum() int result = sumUtil.sum(10, 20); System.out.println("两数之和:" + result); // 输出:30 }
}
**注意:** * `public` 函数只能访问同一包或子包中的其他 `public` 成员。 * `public` 函数还可以在其他包中访问,但需要显式导入包含该函数的类。
The above is the detailed content of Java function access permission modifier public usage guide. For more information, please follow other related articles on the PHP Chinese website!