16 クラスを使う
dotinstall.com
クラスとは
- 関連のある変数や関数をまとめて管理出来る
- クラスの中の変数->
プロパティ
- クラスの中の関数->
メソッド
- クラスを使う時は
インスタンス
というデータの実体を作る
クラスを作る
- クラスのプロパティは初期化されるかOptionalになる必要があるので、以下はエラーになる
class Student {
var name: String TODO
var number: Int TODO
var appear: Int = 0
func sayHello() {
println("出席番号 \(number), \(name) say hello")
}
func update() {
appear++
}
}
- イニシャライザーを作って初期化
- インスタンス化してプロパティ等にアクセス
class Student {
var name: String
var number: Int
var appear: Int = 0
init (name: String, number: Int) {
self.name = name
self.number = number
}
func sayHello() {
println("出席番号 \(number), \(name) say hello")
}
func update() {
appear++
}
}
var yasumoto = Student(name: "ayaka", number: 5)
yasumoto.name
yasumoto.number
yasumoto.sayHello()
yasumoto.appear
yasumoto.update()
yasumoto.appear
17 クラスの継承
dotinstall.com
継承とは
できること
- 親クラスで定義されたプロパティ、メソッドを全部使うことが出来る
- 親クラスのメソッドを
override
できる
override
を禁止することが出来る
- 親クラスのメソッド、プロパティを呼ぶことが出来る
class Student {
var name: String
var number: Int
var appear: Int = 0
init (name: String, number: Int) {
self.name = name
self.number = number
}
func sayHello() {
println("出席番号 \(number), \(name) say hello")
}
final func update() {
appear++
}
}
class ExchangeStudent: Student {
func reset() {
appear = 0
}
override func sayHello() {
super.sayHello()
println("出席番号 \(number) は永久欠番です!!")
}
}
var yasumoto = Student(name: "ayaka", number: 5)
yasumoto.name
yasumoto.number
yasumoto.sayHello()
yasumoto.appear
yasumoto.update()
yasumoto.appear
var hirono = ExchangeStudent(name: "suzuki", number: 8)
hirono.name
hirono.number
hirono.appear
hirono.update()
hirono.appear
hirono.reset()
hirono.appear
hirono.sayHello()
dotinstall.com
- 以下のような問題を解決してくれて便利なもの
- すべてのプロパティを受け継がなくていい
- クラスの継承では親クラスを複数持つことができない
- 継承関係がないような複数のクラスに似たような機能を持たせることを保証することができる
protocol Idol {
var group: String {get set}
func sayGroupName()
}
class Student: Idol {
var name: String
var number: Int
var appear: Int = 0
var group: String = "EBC"
func sayGroupName() {
println("We are \(group)!!!")
}
init (name: String, number: Int) {
self.name = name
self.number = number
}
func sayHello() {
println("出席番号 \(number), \(name) say hello")
}
final func update() {
appear++
}
}
var yasumoto = Student(name: "ayaka", number: 5)
yasumoto.group
yasumoto.sayGroupName()