728x90
클래스와 객체의 정의

클래스와 객체의 정의

  • 객체지향 : 절차 중심의 코드를 구조적으로 하고자 함
    • 구조적인 코드 구조를 클래스 / 객체를 이용하여 실제 세계와 비슷하게 작성
    • 객체와 그 관계를 표현하여 확장 - 재사용이 용이
  • 객체지향 용어
    • 추상화(abstraction) : 어떠한 내용을 개념화하는 작업 - 클래스의 기본 형식 구성
    • 인스턴스(Instance) : 클래스 객체 생성
    • 상속(Inheritance) : 부모 클래스의 내용을 자식 클래스로 물려받음
    • 다형성(polymorphism) : 하나의 이름으로 다양한 처리를 제공
    • 캡슐화(encapsulation) : 메소드 내용은 외부 사용자가 접근할 수 없게 함
    • 메시지 전송 : 객체 간의 데이터 교환
    • 연관 : 클래스 간의 관계
  • 언어 별 동의어(코틀린 : 그 외 언어들)
    • 클래스 : 분류, 범주
    • 프로퍼티(Property) : 속성(Attribute), 변수(Variable), 필드(Field), 데이터(Data)
    • 메서드(Method) : 함수(Function), 동작(Operation), 행동(Behavior)
    • 객체(Object) : 인스턴스(Instance)

클래스 생성자 (Constructor)

  • 클래스 생성 시 호출되는 함수
    • 객체 생성 시 필요한 값을 인자로 설정 가능
  • 주 생성자(Primary Constructor) : 클래스명과 함께 기재, 보통 constructor 키워드는 생략 가능
  • 부 생성자 (Secondary Constructor) : 클래스명 본문에 기재, 하나 이상의 부생성자를 정의 가능
class Bird { //프로퍼티 var name : String = "noname" var wing : Int //생성자 constructor(name:String, wing : Int) { this.name = name //생성자, 메소드에서 클래스 프로퍼티 참조 this.wing = wing } //메소드 fun fly() { println("Fly!") } } fun main() { val coco = Bird("coco", 2) coco.fly() }

상속(Inheritance)

  • 자식 클래스가 상위(부모) 클래스 내용을 계승
  • 상위 클래스의 프로퍼티와 메소드가 하위로 적용됨
  • open class (class명) : 클래스를 상속 가능한 상태로
    • class (클래스명) : (상위 클래스명) : 클래스 상속
    • 코틀린 클래스는 묵시적으로 Any 클래스로부터 상속됨
open class Bird(var name : String, var wing : Int) //pri. Constructor, 프로퍼티 선언한 상위 클래스 { fun fly() { println("Fly!") } } class Lark(name : String, wing : Int) : Bird() //클래스 상속 : 상위 클래스의 프로퍼티와 동일하게 Construct { fun singalong { print("sing together") } } class Parrot : Bird() { var language : String //만약 하위 클래스에 새 프로퍼티 추가 시 별도로 선언 constructor(name : String, wing : Int, language : String) : super(name, wing) //부생성자로 클래스 상속 시 super 키워드 사용 { this.language = "..." } fun speak() { println("hello?") } } fun main() { var lark = Lark("mylark", 2) var parrot = Parrot("myparrot", 2, "Eng") }

다형성(Polymorphism)

  • 같은 이름을 사용하지만 매개변수가 다른 함수
    • 하나의 이름으로 여러 기능 수행
    • static polymorphism : 컴파일 시점의 다형성, 메소드 오버로딩
    • dynamic polymorphism : 런타임 다형정, 메소드 오버라이딩
  • 오버라이딩
    • 기능을 바꾸어 재설계
    • ex. push() - 확인 / 취소 로 서로 다른 기능을 수행하게 할 수 있음
    • 클래스 상속과 같이 open으로 상위 메소드에 선언해주고, override로 상속
    • final override 사용 시 오버라이드를 선언한 클래스의 하위 클래스는 재정의 금지
  • 오버로딩
    • 같은 기능을 구현하지만 인자 수나 타입이 다름
    • ex. print("hello") (string), print(1)(int)와 같이 같은 출력이지만 받는 인자가 다름
fun add(x:Int):Int { return x+1 } fun add(x:Double) : Double { return x+1.0 //오버로딩 : 다른 type } fun add(x:Int, y:Int) : Int { return x+y //오버로딩 : 다른 인자 개수 }

super, this

  • super
    • 상위 클래스의 참조
    • super.프로퍼티, super.메소드(), super() : 프로퍼티, 메소드, 생성자 참조
  • this
    • 현재 클래스의 참조
    • this.프로퍼티, this.메소드, this() : 프로퍼티, 메소드, 생성자 참조
open class Person { //상위 클래스 constructor(firstName: String) { println("[Person] firstName: $firstName") } constructor(firstName: String, age: Int) { //생성자 오버로딩 println("[Person] firstName: $firstName, $age") } } class Developer: Person { //Person 클래스 상속 constructor(firstName: String): this(firstName, 10) { // Developer 클래스의 아래 constructor 접근 (age default로 10 대입) println("[Developer] $firstName") } constructor(firstName: String, age: Int): super(firstName, age) { // Developer Class의 상위 클래스인 Person Class의 생성자 접근 println("[Developer] $firstName, $age") } }
  • 외부 클래스 호출(@)
    • 클래스 내부의 클래스(inner class)에서 상위 클래스 호출 시 super@클래스명으로 호출한다.
  • 앵글브라켓(<>)
    • 클래스와 인터페이스 중복 사용 시 사용할 상위 클래스를 지정 가능
open class A { open fun f() = println("A class f") fun a() = println("A class a") } interface B { fun f() = println("B interface f") fun b() = println("B interface b") } class C : A(), B { override fun f() = println("C class f") fun testing() { f() //C클래스의 f b() //B 인터페이스의b super<A>.f() //A클래스의 f super<B>.f() //B클래스의 f } }

가시성 지시자와 캡슐화

  • 클래스를 작성할 때 클래스 외부로부터 접근을 차단하는 속성이나 기능
  • 가시성 지시자(visibility modifier)
    • private : 클래스 내부에서만 접근 가능
    • public : 접근 가능(기본값)
    • protected : 상속된 클래스만 접근 가능
    • internal : 같은 모듈 내에서만 접근 가능
    • 변수명, 함수명, 클래스명, 지시자 등에 붙을 수 있음
728x90

+ Recent posts