10์ผ์ฐจ: 100DaysOfSwift๐Ÿš€

2464 ๋‹จ์–ด 100daysofswiftswiftiosswiftui
10์ผ์ฐจ
ํด๋ž˜์Šค์™€ ์ƒ์†

์ƒ์ˆ˜, ๋ณ€์ˆ˜ ๋ฐ ํ•จ์ˆ˜์™€ ๋งˆ์ฐฌ๊ฐ€์ง€๋กœ ์‚ฌ์šฉ์ž๊ฐ€ ํด๋ž˜์Šค ์†์„ฑ ๋ฐ ๋ฉ”์„œ๋“œ๋ฅผ ์ •์˜ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

ํด๋ž˜์Šค๋Š” ์†์„ฑ๊ณผ ๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์ƒˆ ์œ ํ˜•์„ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋‹ค๋Š” ์ ์—์„œ ๊ตฌ์กฐ์ฒด์™€ ์œ ์‚ฌํ•˜์ง€๋งŒ 5๊ฐ€์ง€ ์ค‘์š”ํ•œ ์ฐจ์ด์ ์ด ์žˆ์Šต๋‹ˆ๋‹ค.

๋‚˜๋งŒ์˜ ์ˆ˜์—… ๋งŒ๋“ค๊ธฐ

ํด๋ž˜์Šค์™€ ๊ตฌ์กฐ์ฒด์˜ ์ฒซ ๋ฒˆ์งธ ์ฐจ์ด์ ์€ ํด๋ž˜์Šค์—๋Š” ๋ฉค๋ฒ„๋ณ„ ์ด๋‹ˆ์…œ๋ผ์ด์ €๊ฐ€ ์ œ๊ณต๋˜์ง€ ์•Š๋Š”๋‹ค๋Š” ๊ฒƒ์ž…๋‹ˆ๋‹ค. ์ฆ‰, ํด๋ž˜์Šค์— ์†์„ฑ์ด ์žˆ๋Š” ๊ฒฝ์šฐ ํ•ญ์ƒ ๊ณ ์œ ํ•œ ์ดˆ๊ธฐํ™” ํ”„๋กœ๊ทธ๋žจ์„ ๋งŒ๋“ค์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.

class FullName {
    var firstName: String
    var lastName: String

    init(firstName: String, lastName: String) {
        self.firstName = firstName
        self.lastName = lastName
    }
}

let FName = FullName(firstName: "Saurabh", lastName: "Chavan")
print(FName.firstName)
//Saurabh


ํด๋ž˜์Šค ์ƒ์†

์ƒ์†์„ ํ†ตํ•ด ๊ธฐ์กด ํด๋ž˜์Šค์—์„œ ์ƒˆ ํด๋ž˜์Šค๋ฅผ ๋งŒ๋“ค ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

์ƒ์„ฑ๋˜๋Š” ์ƒˆ ํด๋ž˜์Šค๋Š” ํ•˜์œ„ ํด๋ž˜์Šค(์ž์‹ ๋˜๋Š” ํŒŒ์ƒ ํด๋ž˜์Šค)๋ผ๊ณ  ํ•˜๋ฉฐ ํ•˜์œ„ ํด๋ž˜์Šค๊ฐ€ ํŒŒ์ƒ๋˜๋Š” ๊ธฐ์กด ํด๋ž˜์Šค๋Š” ์ˆ˜ํผ ํด๋ž˜์Šค(๋ถ€๋ชจ ๋˜๋Š” ๊ธฐ๋ณธ ํด๋ž˜์Šค)๋ผ๊ณ  ํ•ฉ๋‹ˆ๋‹ค.

์ฝœ๋ก  :์„ ์‚ฌ์šฉํ•˜์—ฌ ๋‹ค๋ฅธ ํด๋ž˜์Šค์—์„œ ํด๋ž˜์Šค๋ฅผ ์ƒ์†ํ•ฉ๋‹ˆ๋‹ค.

ํ†ต์‚ฌ๋ก :

// define a superclass
class Animal {
  // properties and methods definition
}

// inheritance
class Dog: Animal {

  // properties and methods of Animal
  // properties and methods of Dog
}


์—ฌ๊ธฐ์„œ๋Š” Animal ์Šˆํผํด๋ž˜์Šค์—์„œ Dog ์„œ๋ธŒํด๋ž˜์Šค๋ฅผ ์ƒ์†ํ•ฉ๋‹ˆ๋‹ค.

์˜ˆ์‹œ:

class Animal {

  // properties and method of the parent class
  var name: String = ""

  func eat() {
    print("I can eat")
  }
}

// inherit from Animal
class Dog: Animal {

  // new method in subclass
  func display() {

    // access name property of superclass
    print("My name is ", name);
  }
}

// create an object of the subclass
var labrador = Dog()

// access superclass property and method 
labrador.name = "Rohu"
labrador.eat()

// call subclass method 
labrador.display()

**Output**

I can eat
My name is Rohu


์˜ˆ 2:

class Sau {
    var name:String = ""
}

class Saurabh:Sau {
    func display(){
        print("My name is",name)
    }
}

let FName = Saurabh()
FName.name = "Saurabh"
FName.display()
//output
My name is Saurabh


์žฌ์ •์˜ ๋ฐฉ๋ฒ•

์ž์‹ ํด๋ž˜์Šค๋Š” ๋ถ€๋ชจ ๋ฉ”์„œ๋“œ๋ฅผ ์ž์ฒด ๊ตฌํ˜„์œผ๋กœ ๋Œ€์ฒดํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค(์˜ค๋ฒ„๋ผ์ด๋”ฉ์ด๋ผ๊ณ  ํ•˜๋Š” ํ”„๋กœ์„ธ์Šค).

์Šˆํผํด๋ž˜์Šค์™€ ์„œ๋ธŒํด๋ž˜์Šค ๋ชจ๋‘์— ๋™์ผํ•œ ๋ฉ”์„œ๋“œ๊ฐ€ ์ •์˜๋˜์–ด ์žˆ์œผ๋ฉด ์„œ๋ธŒํด๋ž˜์Šค ํด๋ž˜์Šค์˜ ๋ฉ”์„œ๋“œ๊ฐ€ ์Šˆํผํด๋ž˜์Šค์˜ ๋ฉ”์„œ๋“œ๋ฅผ ์žฌ์ •์˜ํ•ฉ๋‹ˆ๋‹ค. ์ด๋ฅผ ์žฌ์ •์˜๋ผ๊ณ  ํ•ฉ๋‹ˆ๋‹ค.

ํ†ต์‚ฌ๋ก :

class Vehicle {

  func displayInfo(){
    ... 
  }
}

class Car: Vehicle {

  // override method
  override func displayInfo() {
    ... 
  }   
} 

์ข‹์€ ์›นํŽ˜์ด์ง€ ์ฆ๊ฒจ์ฐพ๊ธฐ