Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

The keyword public

The keyword public: The public modifier gives a declaration the widest accessibility allowed by its context, package, and module boundary.

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

public

The public modifier gives a declaration the widest accessibility allowed by its context, package, and module boundary.

Keep public APIs small and stable, document their contracts, and export only packages intended for consumers.

A public type in an unexported module package is unavailable to other modules. For file-system storage, a host implementation may optionally require a public top-level type name to match its file name; this is not a universal language requirement.

An inherited public member can still be unreachable through an inaccessible qualifier type; public implies neither immutability nor security.

The call prints hello, while class-public=true and method-public=true confirm the public class and method.

Examples

public class Main { public static final class Api { public String greet(){return "hello";} } public static void main(String[] a)throws Exception{System.out.println(new Api().greet());System.out.println("class-public="+java.lang.reflect.Modifier.isPublic(Api.class.getModifiers()));System.out.println("method-public="+java.lang.reflect.Modifier.isPublic(Api.class.getMethod("greet").getModifiers()));} }

Result

hello
class-public=true
method-public=true

The call prints hello, while class-public=true and method-public=true confirm the public class and method.

Sources