Swift 4 Programming #15 – Inheritance and Overriding
class จะให้ properties , method
inheritance
มี parent , child class
การใช้จาก parent class หมายถึง เอา method จาก parent มาใช้

class Parent {
    func parentMethod() {
        print("This is a parent method")
    }
}

var p = Parent()
p.parentMethod()

var p = Parent(): เป็นการสร้าง instance of the Parent class และ assign ให้กับ variable p

ส่วนการสร้าง child class ก็คือเกี่ยวกับ parent มาด้วย (และอาจจะเพิ่มเฉพาะของ child ลงไป

class Child: Parent {
    func childMethod() {
        print("This is a child method")
    }
}

var c = Child()
c.childMethod()
c.parentMethod()

class Child: Parent { … }: The Child class inherits from the Parent class.

ใน parent มันมีทั้ง unique and general method , child เอา method ของ parent มาใช้ แต่ปรับให้เป็นของตัวเอง เรียก overriding

class Parent {
    func parentMethod() {
        print("This is a parent method")
    }

    func getName() {
        print("This is a parent")
    }
}

var p = Parent()
p.parentMethod()

class Child: Parent {
    func childMethod() {
        print("This is a child method")
    }

    override func getName() {
        print("This is a child")
    }
}

var c = Child()
c.childMethod()
c.parentMethod()
c.getName()

child มันเอา getName มา แต่ต้องเปลี่ยนเป็นของมัน , ต้องมี override นำหน้าด้วย

Overriding methods – Swift in Sixty Seconds

Swift: Override Method

Discover more from อรรถพรคลินิก ศัลยกรรมตกแต่ง Attaporn Plastic Surgery clinic 阿塔蓬博士,曼谷整形外科医生

Subscribe now to keep reading and get access to the full archive.

Continue reading