可见性

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

7. private fun findISBN(): String = "978-7-111-44250-9"
8. protected fun findAuthor(): String = "Cay"
9. public fun findName(): String = "Core Java"
10. internal fun findPages(): Int = 300
11. }

对应的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;

9. @NotNull
10. protected final String getAuthor() {
11. return this.author;
12. }

14. protected final void setAuthor(@NotNull String var1) {
15. Intrinsics.checkParameterIsNotNull(var1, "<set-?>");
16. this.author = var1;
17. }

19. @NotNull
20. public final String getName() {
21. return this.name;
22. }

24. public final void setName(@NotNull String var1) {
25. Intrinsics.checkParameterIsNotNull(var1, "<set-?>");
26. this.name = var1;
27. }

29. public final int getPages$production_sources_for_module_chapter10_interoperability_main() {
30. return this.pages;
31. }

33. public final void setPages$production_sources_for_module_chapter10_interoperability_main(int var1) {
34. this.pages = var1;
35. }

37. private final String findISBN() {
38. return "978-7-111-44250-9";
39. }

41. @NotNull
42. protected final String findAuthor() {
43. return "Cay";
44. }

46. @NotNull
47. public final String findName() {
48. return "Core Java";
49. }

51. public final int findPages$production_sources_for_module_chapter10_interoperability_main() {
52. return 300;
53. }
54. }

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