Skip to content

2.5 클래스 #30

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
thals0 opened this issue Jan 11, 2024 · 0 comments
Open

2.5 클래스 #30

thals0 opened this issue Jan 11, 2024 · 0 comments

Comments

@thals0
Copy link
Owner

thals0 commented Jan 11, 2024

2.5 클래스

클래스란 객체를 정의하는 설계도

함수 vs 메서드

함수 : 어떠한 기능을 수행하는 코드 형식

메서드 : 클래스 내부에 선언되어 있는 함수

클래스 선언 및 객체 선언

class Car

class 키워드와 클래스 이름만으로도 클래스를 만들 수 있음 (기능 없음)

class Car(val color:String) 
val car = Car("red") // 객체 생성
println("My car color is ${car.color}") // 객체의 color 프로퍼티 사용

클래스 생성자

  1. 주 생성자

    1. 클래스 이름 옆에 괄호로 둘러쌓인 코드
    class Person constructor(name: String){}
    class Person2(name: String){} // 키워드 constructor 생략 가능
    class Person3(val name: String){} // val 이나 var를 사용해서 선언과 초기화 한 번에 수행
  2. 보조 생성자

    클래스 바디 내부에서 constructor 키워드를 이용해 만들어, 객체 생성 시 실행할 코드를 작성해 넣을 수 있음

    class Person4 {
        constructor(age: Int) {
            println("i'm $age years old")
        }
    }

    주 생성자가 존재할 때는 반드시 this 키워드를 통해 주 생성자를 호출해야 함

    class Person5 (name:String){
        constructor(name:String, age: Int): this(name){
            println("i'm $age years old")
        }
    }
  3. 초기화 블록

    객체 생성 시 필요한 작업을 하는 것

    init{} 안의 코드들은 객체 생성 시 가장 먼저 실행되고 주 생성자의 매개변수를 사용할 수 있음

    주로 생성자와 같이 쓰임

    class Person6(name: String){
        val name: String
        init {
            if (name.isEmpty()){
                throw IllegalArgumentException("이름이 없어요.")
            }
            this.name = name
        }
    }
    val newPerson = Person6("") // 에러 발생

클래스의 상속

open 키워드 사용

메서드도 자식 클래스에서 오버라이드 하려면 부모 클래서의 메서드에 open 키워드를 추가해야 함

// 예시 1
open class Flower {
    open fun waterFlower(){
        println("water flower")
    }
}
class Rose: Flower(){
    override fun waterFlower() {
        super.waterFlower()
        println("Rose is happy now")
    }
}
val rose = Rose()
rose.waterFlower()
// 예시 2
open class Flower(var name:String) {}
class Rose(name: String, val color: String): Flower(name){}
val rose = Rose("rose", "red")
println(rose.name)
println(rose.color)
접근제어자 설명
public 어디에서나 접근 가능
internal 같은 모듈 내에서 접근 가능 (안드로이드 개발 시 한 프로젝트 안에 있으면 같은 모듈임)
protected 자식 클래스에서는 접근할 수 있음
private 해당 클래스 내부에서만 접근할 수 있음

컴패니언 객체: companion 키워드

자바의 static 키워드와 유사

object 키워드를 사용해서 만들어진 객체는 여러 번 호출되더라도 딱 하나의 객체만 생성되어 재사용됨

추상 클래스

그 자체로는 객체를 만들 수 없는 클래스

일반적으로 추상 메서드가 포함된 클래스를 말함

(추상 메서드 : 아직 구현되지 않고 추상적으로만 존재하는 메서드)

abstract 키워드

상속받는 자식 클래스에 특정 메서드 구현을 강제하고 싶을 때 사용

추상 클래스 자체로는 직접 객체를 만들 수 없음

데이터 클래스

특정한 메서드의 실행보다는 데이터 전달 목적이 있음

data class : 데이터 전달용 객체(data transfer object)를 간편하게 생성하도록 도와줌

주 생성자에는 반드시 val이나 var를 사용한 프로퍼티 정의가 적어도 하나 이상 필요 (val, var이 아닌 매개변수는 사용할 수 없음)

toString(), toCopy() 메서드 자동으로 만들어 줌

toString() 객체에 포함되어 있는 데이터를 출력하여 볼 수 있음 / 생성자에 포함된 프로퍼티만 출력
toCopy() 객체의 속성들을 복사하여 변환하는 메서드 / 인수로 받은 프로퍼티만 해당 값으로 바뀌어 복사해줌
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant