[Kotlin] 접근 제한자

강승구·2023년 1월 1일
0

접근제한자는 객체가 공개되어야 하는 범위를 정해주는 역할을 한다.
즉 변수나 함수, 클래스 멤버 등의 참조 범위를 지정한다.

코틀린에서는 private, protected, internal, public 의 접근 제한자를 제공하고 있다.


접근 제한자의 종류

  • public : 코틀린의 기본 접근 제한자로써 어디에서나 접근할 수 있다.
  • private : 해당 코틀린 파일 또는 클래스 내에서만 접근 가능하다.
  • protected : 해당 코틀린 파일 또는 클래스 내에서와 자식 클래스에서는 접근이 가능하다. top-level에서는 선언할 수 없다.
  • internal : 같은 모듈 내에서 어디서든 접근 가능하다.

접근 제한자를 아무것도 붙이지 않으면 public으로 선언된다.

접근 제한자를 가질 수 있는 요소로는 class, object, interface, constructor, function, property 등이 있고, 로컬 변수, 로컬 함수, 로컬 클래스는 접근 제한자를 선언할 수 없다.


생성자의 접근 제한자

아무 키워드도 설정하지 않은 생성자는 public 생성자이다. 즉 누구나 접근이 가능하다.
internal을 붙이면 모듈 내에서만 접근 가능하다.
private을 붙이면 클래스 내에서만 접근이 가능하여 외부에서 접근할 수 없다.

생성자의 접근 제한자는 다음과 같이 설정할 수 있다.

class Code private constructor(a: Int) {
	...
}

예제

open class Fruit{
    val name = "전체공개"   // 아무 키워드도 주지 않으면 기본적으로 public 으로 세팅
    private val vendor:String = "두콩상회"
    protected val vender1:String = "두콩상회(protected)"
    internal val vender2:String = "두콩상회(internal)"

    fun getVender1():String {
        return vender1
    }
}

class Apple : Fruit() {
    fun get_vender1() : String {
        return vender1
    }
}

fun main(){
    val aFruit : Fruit = Fruit()
    val anApple : Apple = Apple()

// public 멤버 접근
    println(aFruit.name)

// private 멤버 접근
//println(aFruit.vender) // 컴파일 에러
    println(aFruit.getVender1())

// protected 멤버 접근
// 확장클래스(상속받은 클래스)에서 protected 멤버인 vender1 에 접근
    println(anApple.get_vender1())

// internal 멤버 접근 
// 확장클래스(상속받은 클래스)에서 internal 멤버인 vender2 에 접근
    println(anApple.vender2)
}
profile
강승구

0개의 댓글