Junior — Middle
Explain the differences in using the protected access modifier in Java and Kotlin.
sobes.tech AI
Answer from AI
In Java, the access modifier protected means that a class member is accessible:
- Within the class itself
- In all subclasses (even if they are in a different package)
- In all classes within the same package
That is, protected in Java is a combination of access by inheritance and by package.
In Kotlin, however, protected means access only within the class itself and its subclasses, but not accessible from other classes in the same package. Kotlin does not have the concept of package-level access, so protected is more restrictive than in Java.
Example:
// Java
package pkg1;
public class A {
protected int x = 10;
}
package pkg1;
public class B {
void test() {
A a = new A();
int val = a.x; // Accessible, since in the same package
}
}
package pkg2;
public class C extends A {
void test() {
int val = x; // Accessible, since subclass
}
}
// Kotlin
open class A {
protected val x = 10
}
class B : A() {
fun test() {
println(x) // Accessible, subclass
}
}
class C {
fun test() {
val a = A()
// println(a.x) // Error: protected not accessible outside class and subclasses
}
}
Thus, the main difference is that in Kotlin protected does not provide package-level access, only inheritance-based access, whereas in Java it provides both inheritance and package access.