WissensdatenbankPrüfungszentrum
DEDeutsch
Sprache wählen13

CKTIS / Java

Das Schlüsselwort public

Das Schlüsselwort public: Der Modifizierer public gibt einer Deklaration die weiteste durch Kontext, Paket und Modulgrenze erlaubte Zugänglichkeit.

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

Syntax

public

Der Modifizierer public gibt einer Deklaration die weiteste durch Kontext, Paket und Modulgrenze erlaubte Zugänglichkeit.

Halte öffentliche APIs klein und stabil, dokumentiere Verträge und exportiere nur für Verbraucher bestimmte Pakete.

Ein public Typ in nicht exportiertem Modulpaket ist anderen Modulen unzugänglich. Bei Dateispeicherung darf die Hostimplementierung optional verlangen, dass der Name eines öffentlichen Top-Level-Typs zum Dateinamen passt; dies ist keine universelle Sprachregel.

Ein geerbtes public Element kann über einen unzugänglichen Qualifizierertyp unerreichbar bleiben; public bedeutet weder Unveränderlichkeit noch Sicherheit.

Der Aufruf liefert hello; class-public=true und method-public=true bestätigen Klasse und Methode.

Beispiele

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()));} }

Ergebnis

hello
class-public=true
method-public=true

Der Aufruf liefert hello; class-public=true und method-public=true bestätigen Klasse und Methode.

Quellen