Kotlin(코틀린) 기본문법 5. 클래스와 객체

차선호·2023년 4월 2일
0

Kotlin

목록 보기
5/8
post-thumbnail

클래스와 객체


OOP (Object - Oriented Programming)

  • 객체 지향 프로그래밍

  • 절차적 프로그래밍의 한계를 극복하고자 나온 한 가지의 방법론

  • 객체 간 상호작용으로서 표현하는 프로그래밍

  • 객체의 관계를 표현하고 이를 통해 확장과 재사용이 용이

  • 자바, 코틀린에서는 OOP를 지원

객체지향 용어

  • 클래스(Class)

    • 대상들을 분류하고 특징(속성)과 동작(함수)을 작성한 것
  • 추상화

    • 목표로 하는 것에 대해 필요한 만큼 속성과 동작을 정의하는 과정
  • 객체지향 개념의 동의어들

    • 코틀린에서 사용하는 용어 그 밖에 용어

      • 프로퍼티(Property) / 속성(Attribute) / 변수(Variable) / 필드(Field) / 데이터(Data)
      • 메서드(Method) / 함수(Function) / 동작(Operation) / 행동(Begivior)
      • 객체(Object) / 인스턴스(Instance)
    • 자바에서 사용하는 필드는 코틀린에서 프로퍼티라 불림

클래스 선언

  • 빈 형태의 선언
    class Computer{ //내용이 비어있는 클래스 선언
    }
  • 클래스 내에 프로퍼티와 메서드가 정의된 경우
    class Bird{
    	//프로퍼티 저으이
    	//메서드 정의
    }

클래스와 객체

  • Computer 클래스 만들기
    class Computer{ //클래스 정의
        //프로퍼티(속성)
        var name: String = "myComputer"
        var part: Int = 2
        var color: String = "blue"
    
        //메소드(함수)
        fun play() = println("computer part : $part")
        fun playGame(vol: Int) = println("game vol: $vol")
    }
    fun main() {
        val computer = Computer() //생성자를 통한 객체 생성
        computer.color = "blue" //객체의 프로퍼티에 값 할당
        println("compter.color : ${computer.color}") //객체의 멤버 프로퍼티 읽기
        computer.play() //객체의 멤버 메서드 사용
        computer.playGame(3)
    }
    
    <---실행 결과--->
    compter.color : blue
    computer part : 2
    game vol: 3

인스턴스

  • Computer 클래스는 틀일 뿐 실제 메모리에서 실행되고 있는 것이 아님

  • Heap 메모리에 올라간 객체를 인스턴스라고 함

  • java에서는 new 키워드로 객체를 생성하지만, 코틀린은 별도의 키워드가 없음

    
    val computer = Computer() // 클래스 생성자를 통한 객체의 생성

생성자

  • 클래스를 통해 객체가 만들어질 때 기본적으로 호출되는 함수

  • 객체 생성 시 필요한 값을 인자로 설정 가능

  • 생성자를 위해 특별한 함수인 constructor( )를 정의

    class 클래스명 constructor(필요한 매개변수들...){ //주 생성자 위치
    	...
    	constructor(필요한 매개변수들...){ //부 생성자의 위치
    		//프로퍼티의 초기화
    	}
    }

주 생성자(Primary Constructor)

  • 클래스명과 함께 기술되며 보통의 경우 constructor 키워드를 생략 가능
    class MyDate(var year: Int, var month: Int, var day: Int){ //주생성자
        override fun toString(): String {
            return "MyDate(year=$year, month=$month, day=$day)"
        }
    }
    fun main() {
        var mydate = MyDate(2002,2,2)
        println(mydate)
    }
    
    <---실행 결과--->
    MyDate(year=2002, month=2, day=2)

부 생성자(Secondary Constructor)

  • 클래스 본문에 기술되며 하나 이상의 부 생성자를 정의할 수 있음
    class MyDate(var year: Int){ //주생성자
        var month: Int = 0
        var day: Int = 0
        constructor(year: Int, month: Int): this(year){
            this.month = month
        }
        constructor(year: Int, month: Int, day: Int): this(year, month){
            this.day = day
        }
        override fun toString(): String {
            return "MyDate(year=$year, month=$month, day=$day)"
        }
    }
    fun main() {
        var mydate1 = MyDate(2002)
        println(mydate1)
        var mydate2 = MyDate(2002,2)
        println(mydate2)
        var mydate3 = MyDate(2002,2,2)
        println(mydate3)
    }
    
    <---실행 결과--->
    MyDate(year=2002, month=0, day=0)
    MyDate(year=2002, month=2, day=0)
    MyDate(year=2002, month=2, day=2)

초기화 Block : init block

  • 객체 생성 시 제일 먼저 호출되는 구문
    class MyDate(year: Int){ //주생성자
        var year: Int = 0
        var month: Int = 0
        var day: Int = 0
        init{
            println("init 호출")
            this.year = year
        }
        constructor(year: Int, month: Int): this(year){ //부생성자
            println("부생성자 호출")
            this.month = month
        }
        override fun toString(): String {
            return "MyDate(year=$year, month=$month, day=$day)"
        }
    }
    fun main() {
        var mydate1 = MyDate(2002)
        println(mydate1)
        var mydate2 = MyDate(2002,2)
        println(mydate2)
    }
    
    <---실행 결과--->
    init 호출
    MyDate(year=2002, month=0, day=0)
    init 호출
    부생성자 호출
    MyDate(year=2002, month=2, day=0)

default value 설정

  • 생성자의 선언부에 값을 assign하여 값을 입력받지 않으면 default value로 사용

    class MyDate(var year: Int = 2002, var month: Int, var day: Int){ //주생성자
        override fun toString(): String {
            return "MyDate(year=$year, month=$month, day=$day)"
        }
    }
    fun main() {
        var mydate1 = MyDate(2002,3,3)
        println(mydate1)
        var mydate2 = MyDate(month = 2, day = 2) //default 이외의 값은 '변수명 = 값' 형태로 선언
        println(mydate2)
    }
    
    <---실행 결과--->
    MyDate(year=2002, month=3, day=3)
    MyDate(year=2002, month=2, day=2)
  • default value 선언할 때 var year = 2002로 해도 int로 유추 가능하다고 생각하여 타입 명시를 빼면 안됨!!

    • 외부에서 들어오는 값이기 때문에 어떤 값이 들어올 지 몰라 타입을 명시해줘야 함
profile
dkssud!

0개의 댓글