티스토리 뷰

※ 이해와 학습을 위해 원본 코드의 추가/수정이 있을 수 있습니다.

※ 인프런 강의: 개복치개발자님의 [입문편] 안드로이드를 위한 코틀린(Kotlin) 문법의 학습 기반으로 작성했습니다.

※ InterviewBit Kotlin 설명을 참고합니다.

※ 정보의 공유 사회(https://ddolcat.tistory.com/) 설명 및 예제를 참고합니다.

※ Programize(http://learning.coreref.com/www.programiz.com/kotlin-programming) 설명 및 예제를 참고합니다.

※ Udemy The Complete Android 12 & Kotlin Development Masterclass 설명 및 예제를 참고합니다.


 

  • Class란
// Class란
// function -> 기능
// class -> 설계도 + 기능. 쉽게 말하면 붕어빵틀

fun main() {
   println(Test().a)
   println(Test2("abcd").b)
   Test3().test3Fun()
   println(MyInfo().getMyAge())
   println(MyInfo().getMyName())
   println(MyInfo().getMyLocation())
   
   val dog = Dog("파트라슈", 20)
   println(dog.getMyDogInfo())
   
   val dog2 = Dog("해피",10)
   println(dog2.getMyDogInfo())
   
   initTest()
   initTest().testInitFun()
   
   InitialValue("철수")
   InitialValue("영희",30)
}

class Test {
    val a = "abc"
}

class Test2(str: String){
    val b = str
}

class Test3(){
    fun test3Fun(){
        println("test3Fun 출력")
    }
}

class MyInfo(){
    fun getMyAge() : Int {
        return 20
    }
    
    fun getMyName() : String {
        return "My name is Bokhi"
    }
    
    fun getMyLocation() : String {
        return "Seoul"
    }
}

class Dog(name: String, age: Int){
    val dogName = name
    val dogAge = age
    
    fun getMyDogInfo() : String {
        return "$dogName : $dogAge"
    }
}

class initTest(){
    
    init {
        println("여기에서 뭔가 해주고싶음")
    }
    
    fun testInitFun(){
        println("testInitFun")
    }
}

// class의 초기값 설정
class InitialValue(name: String, age: Int = 20){
    init {
        println(name)
        println(age)
    }
}

결과
===========================
abc
abcd
test3Fun 출력
20
My name is Bokhi
Seoul
파트라슈 : 20
해피 : 10
여기에서 뭔가 해주고싶음
여기에서 뭔가 해주고싶음
testInitFun
철수
20
영희
30
  • 오버로딩(Overloading)이란
// 오버로딩 -> Overloading
// 같은 이름의 메서드를 여러개 가지면서, 매개 변수의 유형과 개수가 다르도록 하는
// over + loading
// 겹겹이 쌓는다?

fun main() {
   
    val c = Calculator()
    c.sum(1,2)
    c.sum(1,2,3)
    c.sum("나는","행복해")
}

class Calculator(){
    fun sum(a : Int, b: Int){
        println(a+b)
    }
    
    fun sum(a : Int, b: Int, c: Int){
        println(a+b+c)
    }
    
    fun sum(a : String, b: String){
        println(a+b)
    }
}

결과
========================
3
6
나는행복해
  • 상속(Inheritance)
// 상속
// 뭔가 물려받기

fun main() {
   Job1()
   Job2()
   Job3()
}

class Job1(){
    init {
        println("코딩########")
        println("일을 합니다")
        println("코딩을 합니다")
    }
}

class Job2(){
    init {
        println("디자인########")
        println("일을 합니다")
        println("디자인을 합니다")
    }
}

open class AllJobs(){
    init {
        println("일반########")
        println("일을 합니다")
    }
}

// 상속하기
class Job3() : AllJobs() {
    init {
        println("마케팅을 합니다")
    }
}

결과
========================
코딩########
일을 합니다
코딩을 합니다
디자인########
일을 합니다
디자인을 합니다
일반########
일을 합니다
마케팅을 합니다
  • 상속과 오버라이딩
// 상속과 오버라이딩
// 상속: 자식 클래스가 부모 클래스의 멤버를 물려받기
// 오버라이딩: 부모 클래스의 메서드를 자식 클래스에서 재정의해서 사용

fun main() {
	//Parents()
	Child()
    Parents2().doing()
    Parents2().disease()
    
    Child2().doing()
    Child2().disease()
}

open class Parents(){
    init {
        println("Parents Class initialized")
        println("이것은 부모입니다")
    }
}

class Child() : Parents() {
    init {
        println("이것은 부모를 상속받은 자식입니다")
    }
}

open class Parents2(){
    
    init {
        println("Parents2 Class initialized")
        println("이것은 부모입니다")
    }
    
    fun doing(){
        println("부모는 자식을 돌봅니다")
    }
    
    // 재정의할 수 있도록
    open fun disease(){
        println("부모는 병이 있습니다")
    }
}

class Child2() : Parents2() {
    
    // 부모 클래스의 함수를 재정의해서 사용
    override fun disease(){
        // 부모 클래스의 함수를 그대로 사용할 때
        //super.disease()
        println("자식은 병이 없습니다")
    }
}


결과
=====================
Parents Class initialized
이것은 부모입니다
이것은 부모를 상속받은 자식입니다
Parents2 Class initialized
이것은 부모입니다
부모는 자식을 돌봅니다
Parents2 Class initialized
이것은 부모입니다
부모는 병이 있습니다
Parents2 Class initialized
이것은 부모입니다
부모는 자식을 돌봅니다
Parents2 Class initialized
이것은 부모입니다
자식은 병이 없습니다
  • 추상 클래스(Abstract)란
// 추상 클래스
// class는 붕어빵틀
// 추상 클래스는 꽉 채워야하는 붕어빵 틀
// 꽉 채워서 붕어빵을 만들어야하는 틀
// 공통적으로 기능을 구현할 때
 
fun main() {
    Bicycle().wheel()
    Bicycle().engine()
    
    motorcycle().wheel()
    motorcycle().engine()
}

open class Car {
    open fun wheel(){
        println("자동차 바퀴가 굴러갑니다")
    }
    
    open fun engine(){
        println("자동차가 움직입니다")
    }
}

class Bicycle() : Car() {
    override fun wheel(){
        println("자전거 바퀴가 굴러갑니다")
    }
}

abstract class Car2 {
    abstract fun wheel()
    abstract fun engine()
}

class motorcycle() : Car2() {
    override fun wheel(){
        println("오토바이 바퀴가 굴러갑니다")
    }
    
    override fun engine(){
        println("오토바이가 움직입니다")
    }
}

결과
============================
자전거 바퀴가 굴러갑니다
자동차가 움직입니다
오토바이 바퀴가 굴러갑니다
오토바이가 움직입니다
  • abstract 클래스-2
abstract class Person(name: String) {

    init {
        println("### Class initiailized ###")
        println("My name is $name.")
    }

    fun displaySSN(ssn: Int) {
        println("My SSN is $ssn.")
    }

    abstract fun displayJob(description: String)
}

class Teacher(name: String): Person(name) {

    override fun displayJob(description: String) {
        println(description)
    }
}

fun main() {
    val jack = Teacher("Jack Smith")
    jack.displayJob("I'm a mathematics teacher.")
    jack.displaySSN(23123)
}

결과
=================
### Class initiailized ###
My name is Jack Smith.
I'm a mathematics teacher.
My SSN is 23123.
  • 인터페이스(Interface)
// 인터페이스
// 추상 클래스와 비슷
// 꼭 채워넣어야하는 붕어빵틀
// 작은 틀이라서 다른 틀에 여러개를 넣을 수 있음 

fun main() {
   println(Car1().wheel())
   println(Car1().engine())
   
   println(Car2().wheel())
   println(Car2().engine())
   println(Car2().autoDriving())
   
   println(Car3().wheel())
   println(Car3().engine())
   println(Car3().autoParking())
}


interface CarClass {
    fun wheel()
    fun engine()
}

class Car1() : CarClass {
    override fun wheel() {
        println("바퀴가 돌아갑니다")
    }
    override fun engine() {
        println("엔진이 돌아갑니다")
    }
}


abstract class CarClass2 {
    abstract fun wheel()
    abstract fun engine()
}

interface CarAutoDriving {
    fun autoDriving()
}

interface CarAutoParking {
    fun autoParking()
}

class Car2() : CarClass2(), CarAutoDriving {
    
    override fun wheel() {
        println("바퀴가 돌아갑니다")
    }
    override fun engine() {
        println("엔진이 돌아갑니다")
    }
    
    override fun autoDriving(){
        println("자율 주행")
    }
}

class Car3() : CarClass2(), CarAutoParking {
    override fun wheel() {
        println("바퀴가 돌아갑니다")
    }
    override fun engine() {
        println("엔진이 돌아갑니다")
    }
    
    override fun autoParking(){
        println("자동 주차")
    }
}

결과
====================================
바퀴가 돌아갑니다
kotlin.Unit
엔진이 돌아갑니다
kotlin.Unit
바퀴가 돌아갑니다
kotlin.Unit
엔진이 돌아갑니다
kotlin.Unit
자율 주행
kotlin.Unit
바퀴가 돌아갑니다
kotlin.Unit
엔진이 돌아갑니다
kotlin.Unit
자동 주차
kotlin.Unit
  • 데이터 클래스(Data Class), copy(복사하기)
// 데이터 클래스
// 이름처럼 데이터를 넣어놓는 클래스
// 서버에서 데이터를 받아온 것은 넣을 때 주로 사용


fun main() {
   val justDog = JustDog("파트라슈",10)
   println(justDog.name)
   println(justDog.age)
   println(justDog.toString())
   
   val dataDog = DataDog("해피",20)
   println(dataDog.name)
   println(dataDog.age)
   println(dataDog.toString())
   
   val dataDog2 = dataDog.copy(name = "메리")
   println(dataDog2.name)
   println(dataDog2.age)
   println(dataDog2.toString())
}

class JustDog(var name : String, var age : Int)
data class DataDog(var name : String, var age : Int)

결과
=========================
파트라슈
10
JustDog@31cefde0
해피
20
DataDog(name=해피, age=20)
메리
20
DataDog(name=메리, age=20)
  • 중첩 클래스(Nested Class) / 내부 클래스(Inner Class)
// 중첩 클래스 -> 객체지향 / 캡슐화
// 내부 클래스 -> RecyclerView
// 중첩 클래스에서는 외부에 있는 변수를 사용할 수 없지만,
// 내부 클래스에서는 가능함

fun main() {
   val test1 = Test1.Test1NestedClass()
   test1.testFun1()
   
   val test2 = Test2().Test2InnerClass()
   test2.testFun2()
}


class Test1 {
    
    val tempText1 = "tempText1"
    
    class Test1NestedClass {
        
        fun testFun1(){
            println("TestFun1")
            // println(tempText1) 실행시 Unresolved reference: tempText1 에러 출력
        }
    }
}


class Test2 {
    
    val tempText2 = "tempText2"
    
    inner class Test2InnerClass {
        
        fun testFun2(){
            println("TestFun2")
            println(tempText2)
        }
    }
}

결과
==========================
TestFun1
TestFun2
tempText2
  • Object
// object -> 싱글톤패턴 
// 디자인 패턴 -> 코드를 어떻게 짜는 게 더 좋고, 어떤 방식으로 구성해야 유지보수가 쉬운가
// 객체를 한 개만 생성하도록 한다 / 전역으로 사용 가능

fun main(){
    val test1 = TestClass()
    val test2 = TestClass()
    
    test1.count = 10
    
    println(test1.count)
    println(test2.count)
    
    val test3 = TestObject
    val test4 = TestObject
    
    test3.count = 10
    
    println(test3.count)
    println(test4.count)
    
    val test5 = TestObjectClass()
    val test6 = TestObjectClass()
    
    println("number="+TestObjectClass.number)
    
    test5.plusBtn()
    println("number="+TestObjectClass.number)
    
    test6.minusBtn()
    println("number="+TestObjectClass.number)
}

class TestClass{
    init {
        println("testClass")
    }
    
    var count = 0
}

object TestObject{
     init {
        println("testObject")
    }
     
    var count = 0
}

class TestObjectClass {
    
    companion object {
        var number = 0
    }
    
    fun plusBtn(){
        number++
    }
    
    fun minusBtn(){
        number--
    }
}

결과
================================
testClass
testClass
10
0
testObject
10
10
number=0
number=1
number=0
  • enum
// enum(enumerations) class
// 값을 열거할 때

fun main() {
   println(Direction.NORTH)
   Direction.values().forEach {
       println(it)
   }
   
   val direction = Direction.EAST
    
   when(direction) {
       Direction.NORTH -> {
           println("N")
       } 
       Direction.SOUTH -> {
           println("S")
       } 
       Direction.WEST -> {
           println("W")
       } 
       Direction.EAST -> {
           println("E")
       }  
   } // when(direction):e
   
   val color = Color.RED
    
   when(color) {
       Color.RED -> {
           println(Color.RED.colorName)
       }
       Color.GREEN -> {
           println(Color.GREEN.colorName)
       }
       Color.BLUE -> {
           println(Color.BLUE.colorName)
       }
   } // when(color):e
   
   println(Device.DEVICEON.status)
   
   Device.DEVICEON.status = "OFF"
    
   println(Device.DEVICEON.status)
   
} // main():e

enum class Direction {
    NORTH, SOUTH, WEST, EAST
}

enum class Color( val colorName : String ) {
    RED("빨강"),
    GREEN("초록"),
    BLUE("파랑")
}

enum class Device( var status : String ) {
    DEVICEON("ON"),
    NETWORK("OFF"),
    LOCATION("SEOUL")
}

결과
=====================
NORTH
NORTH
SOUTH
WEST
EAST
E
빨강
ON
OFF
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함