0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

オーバーライド

Posted at
class クラス名: スーパークラス名 {
    override func メソッド名(引数) -> 戻り値の型 {
        メソッド呼び出し時に実行される文
    }
    
    override var プロパティ名: 型名 {
        get {
            return文によって値を返す処理
            superキーワードでスーパークラスの実装を利用できる
        }
        
        set {
            値を更新する処理
            superキーワードでスーパークラスの実装を利用できる
        }
    }
}

オーバーライドとは、スーパークラスで定義されているプロパティやメソッドなどの要素は、サブクラスで再定義することができること。

class User {
    let id: Int
    
    var message: String {
        return "Hello."
    }
    
    init(id: Int) {
        self.id = id
    }
    
    func printProfile() {
        print("id: \(id)")
        print("message: \(message)")
    }
}

class RegisteredUser: User {
    let name: String
    
    override var message: String {
        return "Hello, my name is \(name)"
    }
    
    init(id: Int, name: String) {
        self.name = name
        super.init(id: id)
    }
    
    override func printProfile() {
        super.printProfile()
        print("name: \(name)")
    }
}

let user = User(id: 1)
user.printProfile()

print("---")

let registeredUser = RegisteredUser(id: 2, name: "Yusei Nishiyama")
registeredUser.printProfile()




// 出力
id: 1
message: Hello.
---
id: 2
message: Hello, my name is Yusei Nishiyama
name: Yusei Nishiyama

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?