Swift -继承、属性、重写父类、懒加载、析构函数

版权声明:iOS技术小牛 https://blog.csdn.net/weixin_42925415/article/details/83960973
1.	新建工程命名:zhoukaojineng,创建一个类Person,在类中定义方法eat,实现打印“吃饭”
2.	创建一个继承自Person的Teacher类,在Teacher类中定义方法teach,实现打印“上课”,调用其父类的eat函数
3.	创建一个类Student并继承与Person,定义属性name,在Student中监听属性name的setter和getter
4.	在Student类中重写父类的eat方法,打印“吃了早餐”
5.	在Student类中定义一个只读属性weight,体重“70kg”
6.	在Student类中懒加载一个属性age用来年龄“22岁”,为Student类定一个构造函数,在函数内为所有属性赋值
7.	在Student类中定义一个show方法,用来打印学生信息,函数是公开访问的 
8.	重写Student类的析构函数,在函数内实现所有属性的清空,并打印“调用了析构函数”

1.	新建工程命名:zhoukaojineng,创建一个类Person,在类中定义方法eat,实现打印“吃饭”
import Cocoa

class Person: NSObject {
    func eat(){
        print("吃饭")
    }
}
创建一个继承自Person的Teacher类,在Teacher类中定义方法teach,实现打印“上课”,调用其父类的eat函数
import Cocoa

class Teacher: Person {
    func teach(){
        print("上课")
//        let fulei:Person = Person()
//        fulei.eat()
        super.eat()
        
        
    }
}
创建一个类Student并继承与Person,定义属性name,在Student中监听属性name的setter和getter
在Student类中重写父类的eat方法,打印“吃了早餐”
在Student类中定义一个只读属性weight,体重“70kg”
在Student类中懒加载一个属性age用来年龄“22岁”,为Student类定一个构造函数,在函数内为所有属性赋值
在Student类中定义一个show方法,用来打印学生信息,函数是公开访问的 
重写Student类的析构函数,在函数内实现所有属性的清空,并打印“调用了析构函数”

import Cocoa

class Student: Person {
    //3.    创建一个类Student并继承与Person,定义属性name,在Student中监听属性name的setter和getter
    var name:String = "小明"{
        willSet(newValue){
            print("新名\(newValue)")
        }
        didSet{
            
            print("旧名\(oldValue)")
            
        }
        
    }
    
    //4.    在Student类中重写父类的eat方法,打印“吃了早餐”
    override func eat() {
        print("吃了早餐")
    }
    //5.    在Student类中定义一个只读属性weight,体重“70kg”
    var weight:String{
            return "70kg"
    }
    //6.    在Student类中懒加载一个属性age用来年龄“22岁”,为Student类定一个构造函数,在函数内为所有属性赋值
    lazy var age:String = "22岁"
    init(name:String , age:String){
        super.init()
        self.name = name
        self.age  = age
    }
    
    //7.    在Student类中定义一个show方法,用来打印学生信息,函数是公开访问的
    public func show(){
        print("\(name) , \(age) , \(weight)")
    }
    
    //8.    重写Student类的析构函数,在函数内实现所有属性的清空,并打印“调用了析构函数”
    deinit {
        self.age = ""
        self.name = ""
        print("调用了析构函数")
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_42925415/article/details/83960973