// superclass instance
let p = Person(name: "Tom", age: 20)
print(p.age) // 20
/* subclass instances */
// Student
// ---------------------------------------------
// (o) default values for new properties
// (o) no custom designated inits.
// -> inherits all designated/convenience inits
let s1 = Student(name: "May", age: 17) // inherited designated init
let s2 = Student(name: "Baby") // inherited convenience init
let s3 = Student(seatNo: 23) // custom convenience init
print(s1.seatNo) // 50
print(s2.age) // 0
print(s3.name) // "no name"
// Teacher
// ----------------------------------------------
// (o) default values for new properties
// (x) no custom designated inits.
// (o) implements all superclass designated inits
// -> inherits all superclass convenience inits.
let t1 = Teacher(name: "Joe", age: 35, title: "Dr.") // custom designated init
let t2 = Teacher(name: "Joe", age: 35) // override superclass init
let t3 = Teacher(name: "Babe") // inherited convenience init
print(t1.title) // "Dr."
print(t2.title) // "Mr./Ms."
print(t3.age) // 0
// Master
// -----------------------------------------------
// (x) default values
// -> does not inherit superclass initializers
let m = Master(name: "Sheefu", age: 100, skill: "Kung Fu") // custom designated init
print(m.skill) // "Kung Fu"
// superclass
class Person {
// stored properties
var name: String
var age : Int
// designated: init(name:age:)
init(name:String, age:Int){
self.name = name
self.age = age
}
// convenience: init(name:)
convenience init(name:String){
self.init(name: name, age: 0)
}
}
// (o) default values for new properties
// (o) no custom designated inits.
// -> inherits all designated/convenience inits
class Student: Person {
// stored properties with default values
var seatNo: Int = 50
}
extension Student {
// custom convenience init
convenience init(seatNo: Int) {
// calls inherited designated init
self.init(name: "no name", age: 16)
self.seatNo = seatNo
}
}
// (o) default values for new properties
// (x) no custom designated inits.
// (o) implements all superclass designated inits
// -> inherits all superclass convenience inits.
class Teacher: Person {
var title: String = "Mr./Ms."
// custom designated init
init(name: String, age: Int, title: String) {
self.title = title
super.init(name: name, age: age)
}
// superclass designated -(override)-> subclass convenience
override convenience init(name: String, age: Int) {
self.init(name: name, age: age, title: "Mr./Ms.")
}
}
// (x) default values
// -> does not inherit superclass initializers
class Master: Person {
var skill: String
// custom designated init
init(name: String, age: Int, skill: String){
self.skill = skill
super.init(name: name, age: age)
}
}