Home  >  Article  >  Java  >  Java function access permission modifier public usage guide

Java function access permission modifier public usage guide

PHPz
PHPzOriginal
2024-04-26 08:39:011144browse

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 函数的访问权限修饰符之 public 使用指南

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:

  • Declare functions that need to be accessed from anywhere.
  • Declare methods in a public API or interface.
  • Define tools or utilities for sharing between different packages or classes.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn