Swift -- 8.1 继承
继承
swift支持单继承,一个类只有一个直接父类。
swift中只有类支持继承,枚举和结构体不可以
如果子类对继承得到的属性,方法和下标等不满意,也可以重写父类的属性,方法和下标
与oc不同的是,swift的类不是从一个通用的基类继承而来的,如果不显式地为一个类指定父类,那么该类将没有父类--它并不继承NSObject或Object类
class Fruit
{
var weight = 0.0
func info(){
print("I am a fruit, weight \(weight)")
}
}
class Apple: Fruit {
var name: String!
func taste(){
print("\(name) taste good")
}
}
var a = Apple()
a.weight = 56.0
a.name = "redApple"
a.info()
a.taste()
重写父类的方法
使用override修饰符
如果想要在子类的方法中调用父类中被覆盖的方法,可以使用super关键字
如果子类和父类的方法一样,但是没有使用关键字,就会报错
class Bird {
func fly()
{
print("I can fly")
}
}
class Ostrich: Bird {
override func fly() {
super.fly()
print("I can't fly")
}
}
var os = Ostrich()
os.fly()
重写父类的属性
重写属性这件事就相当于改一下属性里的setter和getter方法
就算之前的属性并不是计算属性,也可以这样写
如果之前的属性是只读属性,(也就是没有setter方法)也可以添上setter方法来改成读写属性
class Brid1{
var speed:Double = 0
}
class Ostrich1: Brid1 {
override var speed : Double{
get{
print("the override attitude is getting")
return super.speed
}
set{
super.speed = newValue * newValue
}
}
}
var oss = Ostrich1()
oss.speed = 20.0
print("the speed is \(oss.speed)")
重写属性观察者
重写属性时可以为继承来的属性添加属性观察者
class Bird3 {
var speed:Double = 0
}
class Ostrich3: Bird3 {
override var speed:Double{
didSet{
print("the speed was changed from \(oldValue) to \(speed)")
}
}
}
var os3 = Ostrich3()
os3.speed = 28.0
print(os3.speed)
//swift中只能通过getter,setter或添加属性观察者的方法来重写属性,不能单纯的定义一个和父属性同名的存储属性,因为没有意义
重写父类的下标
class Base {
subscript(idx:Int) -> Int{
get{
print("the father's get method")
return idx + 10
}
}
}
class Sub: Base {
override subscript(idx:Int) -> Int{
get{
print("the override get method")
print("the super index\(super[idx])")
return idx * idx
}
set{
print("the new value is \(newValue)")
}
}
}
var base = Base()
print(base[7])
var sub = Sub()
print(sub[7])
sub[7] = 90
final关键字
可以用于修饰类,属性,方法,下标
使用final修饰的类不能被继承,派生子类
使用final修饰的属性,方法,下标不可以被重写
final class Base1{
final var name:String = ""
final func say(content:String){
print("Base 实例说:\(content)")
}
final subscript(idx:Int) -> Int{
get{
print("super class get method")
return idx + 10
}
}
}
//下面的会报错
//class Sub1: Base1 {
// override var name : String{
// get{
// return "子类添加的前缀" + super.name
// }
// set{
//
// }
// }
//}

浙公网安备 33010602011771号