W3Cschool
恭喜您成為首批注冊用戶
獲得88經驗值獎勵
type MyDerived(...) = inherit MyBase(...)
在F#中,一個類最多只能有一個直接基類。如果你不使用inherit關鍵字指定基類,這個類隱含從Object繼承。
type Person(name) = member x.Name = name member x.Greet() = printfn "Hi, I'm %s" x.Name type Student(name, studentID : int) = inherit Person(name) let mutable _GPA = 0.0 member x.StudentID = studentID member x.GPA with get() = _GPA and set value = _GPA <- value type Teacher(name, expertise : string) = inherit Person(name) let mutable _salary = 0.0 member x.Salary with get() = _salary and set value = _salary <- value member x.Expertise = expertise //using the subclasses let p = new Person("Mohan") let st = new Student("Zara", 1234) let tr = new Teacher("Mariam", "Java") p.Greet() st.Greet() tr.Greet()
當你編譯和執(zhí)行程序,它產生以下輸出
Hi, I'm Mohan Hi, I'm Zara Hi, I'm Mariam
type Person(name) = member x.Name = name abstract Greet : unit -> unit default x.Greet() = printfn "Hi, I'm %s" x.Name
現(xiàn)在,Person類的問候方法可以在派生類中重寫。下面的例子說明了這一點
type Person(name) = member x.Name = name abstract Greet : unit -> unit default x.Greet() = printfn "Hi, I'm %s" x.Name type Student(name, studentID : int) = inherit Person(name) let mutable _GPA = 0.0 member x.StudentID = studentID member x.GPA with get() = _GPA and set value = _GPA <- value override x.Greet() = printfn "Student %s" x.Name type Teacher(name, expertise : string) = inherit Person(name) let mutable _salary = 0.0 member x.Salary with get() = _salary and set value = _salary <- value member x.Expertise = expertise override x.Greet() = printfn "Teacher %s." x.Name //using the subclasses let p = new Person("Mohan") let st = new Student("Zara", 1234) let tr = new Teacher("Mariam", "Java") //default Greet p.Greet() //Overriden Greet st.Greet() tr.Greet()
當你編譯和執(zhí)行程序,它產生以下輸出
Hi, I'm Mohan Student Zara Teacher Mariam.
[<AbstractClass>] type Person(name) = member x.Name = name abstract Greet : unit -> unit type Student(name, studentID : int) = inherit Person(name) let mutable _GPA = 0.0 member x.StudentID = studentID member x.GPA with get() = _GPA and set value = _GPA <- value override x.Greet() = printfn "Student %s" x.Name type Teacher(name, expertise : string) = inherit Person(name) let mutable _salary = 0.0 member x.Salary with get() = _salary and set value = _salary <- value member x.Expertise = expertise override x.Greet() = printfn "Teacher %s." x.Name let st = new Student("Zara", 1234) let tr = new Teacher("Mariam", "Java") //Overriden Greet st.Greet() tr.Greet()
當你編譯和執(zhí)行程序,它產生以下輸出
Student Zara Teacher Mariam.
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: