可见性

Kotlin 的可见性与Java的可见性的映射关系如下表所示:

Kotlin中的声明 Java中的声明
private private
protected protected
internal public
public public

例如下面的Kotlin代码:

  1. class ProgrammingBook {
  2. private var isbn: String = "978-7-111-44250-9"
  3. protected var author: String = "Cay"
  4. public var name: String = "Core Java"
  5. internal var pages: Int = 300
  6. private fun findISBN(): String = "978-7-111-44250-9"
  7. protected fun findAuthor(): String = "Cay"
  8. public fun findName(): String = "Core Java"
  9. internal fun findPages(): Int = 300
  10. }

对应的Java的代码是:

  1. public final class ProgrammingBook {
  2. private String isbn = "978-7-111-44250-9";
  3. @NotNull
  4. private String author = "Cay";
  5. @NotNull
  6. private String name = "Core Java";
  7. private int pages = 300;
  8. @NotNull
  9. protected final String getAuthor() {
  10. return this.author;
  11. }
  12. protected final void setAuthor(@NotNull String var1) {
  13. Intrinsics.checkParameterIsNotNull(var1, "<set-?>");
  14. this.author = var1;
  15. }
  16. @NotNull
  17. public final String getName() {
  18. return this.name;
  19. }
  20. public final void setName(@NotNull String var1) {
  21. Intrinsics.checkParameterIsNotNull(var1, "<set-?>");
  22. this.name = var1;
  23. }
  24. public final int getPages$production_sources_for_module_chapter10_interoperability_main() {
  25. return this.pages;
  26. }
  27. public final void setPages$production_sources_for_module_chapter10_interoperability_main(int var1) {
  28. this.pages = var1;
  29. }
  30. private final String findISBN() {
  31. return "978-7-111-44250-9";
  32. }
  33. @NotNull
  34. protected final String findAuthor() {
  35. return "Cay";
  36. }
  37. @NotNull
  38. public final String findName() {
  39. return "Core Java";
  40. }
  41. public final int findPages$production_sources_for_module_chapter10_interoperability_main() {
  42. return 300;
  43. }
  44. }

我们可以看到Kotlin中的可见性跟Java中的基本相同。