class A { fn t() { "A::t" } } class B { fn t() { "B::t" } } class C { extends A { fn t() { "(C override A)::t" } } extends B { } fn t() { "C::t" } } class D { extends B { } extends C { fn t() { parent.t() (parent as A).t() (parent as B).t() "(D override C)::t" } } fn t() { "D::t" } } C c = new c() c.t() // C::t (c as A).t() // (C override A)::t (c as B).t() // B::t D d = new D() d.t() // D::t (d as A).t() // (C override A)::t (d as B).t() // B::t (d as C).t() // C::t // (C override A)::t // B::t // (D override C)::t
這裏的as實際上是類型聲明或強制類型轉換。ide
對於類繼承的全部父類,都有一個獨立的域。code
對象經過對不一樣的聲明類型使用不一樣的方法,到達多態的效果,即便類中有多個重名方法也不受影響。對象
class A { fn t() { "A::t" } } class B { fn t() { "B::t" } } class C { extends A { fn t() { "(C override A)::t" } } extends B { fn t() { "(C override B)::t" } } } class D { extends A {} extends B {} } fn c_a_t(c: C(A)) { c.t() } fn c_b_t(c: C(B)) { c.t() } // fn c_t(c: C) { // c.t() // 編譯錯誤!不知道使用哪個t() // } D d = new D() (d as A).t() // A::t (d as B).t() // B::t // d.t() // 編譯錯誤!不知道使用哪個t() // (d as C).t() // 編譯錯誤!不知道使用哪個t() // 可是若是確實要將d多態爲D,就要明確要使用的類 (d as C(A)).t() // (C override A)::t c_a_t.t() // (C override A)::t (d as C(B)).t() // (C override B)::t c_b_t.t() // (C override B)::t
:smirk:繼承