Kotlin 가시성 수정자 – public, protected, internal, private

이 튜토리얼에서는 Kotlin 프로그래밍에서 사용할 수 있는 다양한 가시성 수정자에 대해 논의할 것입니다.

Kotlin 가시성 수정자

가시성 수정자는 Kotlin의 클래스/인터페이스/속성/함수에 추가될 때 해당 요소가 어디에서 보이고 어디에서 접근할 수 있는지 정의합니다. Kotlin의 속성 설정자는 속성과 별도의 수정자를 가질 수 있습니다. 그러나 게터는 가시성 수정자를 정의할 수 없습니다. 속성과 동일한 수정자를 사용합니다. 다음은 가시성 수정자입니다:

  • public
  • protected
  • internal
  • private

공용 수정자

A Public Modifier is the default modifier in Kotlin. Just like the Java public modifier, it means that the declaration is visible everywhere.


class Hello{
}

public class H{
}

fun hi()
public fun hello()

val i = 0
public val j = 5

위의 모든 선언은 파일의 최상위에 있습니다. 모두 공개되어 있습니다. 클래스 멤버의 선언을 언급하지 않으면 (재정의되지 않는 한) 공개됩니다.

보호 수정자

A Protected Modifier in Kotlin: CANNOT be set on top-level declarations. Declarations that are protected in a class, can be accessed only in their subclasses.

open class Pr{
    protected val i = 0
}

class Another : Pr{

    fun iValue() : Int
    {
        return i
    }
}

Pr의 하위 클래스가 아닌 클래스는 `i` 선언에 접근할 수 없습니다. 보호된 경우, 하위 클래스에서 오버라이드될 때 명시적으로 변경하지 않는 한 같은 보호된 수정자를 가지게 됩니다.

open class Pr{
    open protected val i = 0
}

class Another : Pr(){

    fun iValue() : Int
    {
        return i
    }
    
    override val i = 5 //protected visibility
}

Kotlin에서 정의된 보호된 수정자의 개념은 Java와 다릅니다.

내부 수정자

내부는 Kotlin에 있는 새로운 수정자로, Java에는 없습니다. 선언을 내부로 설정하면 해당 모듈 내에서만 사용할 수 있습니다. Kotlin에서 모듈이란 함께 컴파일되는 파일 그룹을 의미합니다.

internal class A {
}

internal val x = 0

이것들은 현재 모듈 외부에서는 보이지 않습니다. 내부 수정자는 사용자로부터 특정 라이브러리 구현을 숨길 필요가 있을 때 유용합니다. 이것은 Java의 패키지-프라이빗 가시성을 사용하여 가능하지 않았습니다.

개인 수정자

개인 수정자는 선언이 현재 범위 외부에서 보이지 않도록 합니다.

var setterVisibility: String = "abc"
private set

open class Pr{
    open protected val i = 0

    fun iValue() : Int
    {
        setterVisibility = 10
        return setterVisibility
    }
}

Kotlin은 여러 최상위 정의를 허용하기 때문에 위 코드가 작동합니다. 아래는 그렇지 않습니다

private open class ABC{
    private val x = 6
}

private class BDE : ABC()
{
    fun getX()
    {
        return x //x cannot be accessed here.
    }
}

x is visibile only from inside its class. We can set private constructors in the following way:

class PRIV private constructor(a: String) {
 ... 
}

{
“error”: “Upstream error…”
}

Source:
https://www.digitalocean.com/community/tutorials/kotlin-visibility-modifiers-public-protected-internal-private