We investigated how kotlin's public
, ʻinternal,
protected,
private and java's
public,
package private,
protected,
private` look like each other.
First, let's see what kind of access rights they have.
public | Accessable from anywhere |
---|---|
protected | Can't declare |
package private | Can be accessed from the same package |
private | Can't declare |
public | Accessable from all classes |
---|---|
protected | Can be accessed from subclasses or classes in the same package |
package private | Can be accessed from classes in the same package |
private | Only accessible from the declared class |
public | Accessable from anywhere |
---|---|
internal | Can be accessed from within the same module |
protected | Can't declare |
private | Only accessible from the declared class |
public | Accessable from all classes |
---|---|
internal | Can be accessed from classes in the same module |
protected | Only accessible from subclasses |
private | Only accessible from the declared file |
Let's get into the main subject from here, let's see what happens when kotlin access modifiers are viewed from Java.
private
classKotlin's private classes are considered package private in java.
A.kt
package com.example.model
private class A(name: String, age: Int, height: Int)
B.java
package com.example.model
public class B {
public B() {
A a = new A("taku", 23, 168); // OK
}
}
C.java
package com.example.ui
public class C {
public C(){
A a = new A("taku", 23, 168) // ERROR
}
}
Java does not have an internal modifier. Therefore, anything marked internal in kotlin is considered public by Java. However, if you are a class member, it will be obfuscated.
A.kt
package com.example.model
internal class A(val name: String, internal val age: Int, private val height: Int)
B.java
package com.example.model
public class B {
public B() {
A a = new A("taku", 23, 168); // OK
a.getName(); // OK
a.getAge(); // ERROR
a.getAge$production_sources_for_module_example(); // OK
a.getHeight(); // ERROR
}
}
Recommended Posts