Sobes.tech
Junior — Middle

Kuidas erinevad juurdepääsumuutujad Java ja Kotlin keeltes?

sobes.tech AI

Vastus AI-lt

In Java and Kotlin, access modifiers serve similar purposes but differ in their set and behavior:

  • Java:

    • public — accessible from anywhere.
    • protected — accessible within the package and in subclasses.
    • (package-private) — accessible only within the package (if no modifier is specified).
    • private — accessible only within the class.
  • Kotlin:

    • public (default) — accessible from anywhere.
    • internal — accessible within the module (for example, within a single Gradle module).
    • protected — accessible in subclasses, but only within the same file (unlike Java, where protected allows access from the package).
    • private — accessible within the class or file (if declared at file level).

The main difference is that in Kotlin, there is the internal modifier, which restricts visibility to the module, and also protected in Kotlin does not give access within the package, only in subclasses. In Java, there is no internal, and protected provides access both in the package and in subclasses.