λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°
iOS 🍎/Swift

Swift12 - 상속

by yongmin.Lee 2021. 2. 2.

Inheritance

A class can inherit methods, properties, and other characteristics from another class. When one class inherits from another, the inheriting class is known as a subclass, and the class it inherits from is known as its superclass. 

 

μŠ€μœ„ν”„νŠΈ 상속

- 클래슀, ν”„λ‘œν† μ½œμ€ 상속이 κ°€λŠ₯ν•˜μ§€λ§Œ μ—΄κ±°ν˜•, κ΅¬μ‘°μ²΄λŠ” 상속이 λΆˆκ°€λŠ₯

- μŠ€μœ„ν”„νŠΈμ˜ ν΄λž˜μŠ€λŠ” λ‹¨μΌμƒμ†μœΌλ‘œ, 닀쀑상속을 μ§€μ›ν•˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€.

- final ν‚€μ›Œλ“œλ₯Ό μ‚¬μš©ν•˜λ©΄ μž¬μ •μ˜(override)λ₯Ό 방지할 수 μžˆμŠ΅λ‹ˆλ‹€.

- static ν‚€μ›Œλ“œλ₯Ό μ‚¬μš©ν•΄ νƒ€μž… λ©”μ„œλ“œλ₯Ό λ§Œλ“€λ©΄ μž¬μ •μ˜κ°€ λΆˆκ°€λŠ₯ ν•©λ‹ˆλ‹€.

- class ν‚€μ›Œλ“œλ₯Ό μ‚¬μš©ν•΄ νƒ€μž… λ©”μ„œλ“œλ₯Ό λ§Œλ“€λ©΄ μž¬μ •μ˜κ°€ κ°€λŠ₯ν•©λ‹ˆλ‹€.

- class μ•žμ— final을 뢙이면 static ν‚€μ›Œλ“œλ₯Ό μ‚¬μš©ν•œκ²ƒκ³Ό λ™μΌν•˜κ²Œ λ™μž‘ν•©λ‹ˆλ‹€.

- override ν‚€μ›Œλ“œλ₯Ό μ‚¬μš©ν•΄ λΆ€λͺ¨ 클래슀의 λ©”μ„œλ“œλ₯Ό μž¬μ •μ˜ ν•  수 μžˆμŠ΅λ‹ˆλ‹€.

 

μƒμ†κ΅¬ν˜„

class Person {
    var name: String = ""
    
    func selfIntroduce() {
        print("μ €λŠ” \(name)μž…λ‹ˆλ‹€")
    }
    
    // final : μž¬μ •μ˜ λΆˆκ°€ λ©”μ„œλ“œ
    final func sayHello() {
        print("hello")
    }
    
    // static :  μž¬μ •μ˜ λΆˆκ°€ νƒ€μž… λ©”μ„œλ“œ
    static func typeMethod() {
        print("type method - static")
    }
    
    // class : μž¬μ •μ˜ κ°€λŠ₯ νƒ€μž… λ©”μ„œλ“œ
    class func classMethod() {
        print("type method - class")
    }
    
    // `final class`λŠ” staticκ³Ό λ˜‘κ°™μ€ μ—­ν•  : μž¬μ •μ˜ λΆˆκ°€
    final class func finalCalssMethod() {
        print("type method - final class")
    }
}

// Person을 μƒμ†λ°›λŠ” Student
class Student: Person {
    var major: String = ""
    
    override func selfIntroduce() {
        print("μ €λŠ” \(name)이고, 전곡은 \(major)μž…λ‹ˆλ‹€")
    }
    
    override class func classMethod() {
        print("overriden type method - class")
    }
    
    // μž¬μ •μ˜ λΆˆκ°€
	// override static func typeMethod() {    }
	// override func sayHello() {    }
	// override class func finalClassMethod() {    }

}

'iOS 🍎 > Swift' μΉ΄ν…Œκ³ λ¦¬μ˜ λ‹€λ₯Έ κΈ€

Swift14 - Optional Chaining  (0) 2021.02.03
Swift13 - Initialization & Deinitialization  (0) 2021.02.02
Swift11 - ν”„λ‘œνΌν‹°  (0) 2021.02.02
Swift10 - first class citizen  (0) 2021.02.02
Swift09 - ν΄λ‘œμ €  (0) 2021.02.02