把类再去分类,就出现了继承。
以Human为例,人有男女之分,男人和女人都是从“人”继承来的。我们建立一个Male类和一个Female类:
public class Male
inherits Human
end class
public class Female
inherits Human
end class
这里Inherits是关键字,表示“继承于...”。
男人也是人,所有人的特质,吃饭睡觉等等,在男人身上都有。所以我们不必再去给Male类定义Eat那些东西了。我们可以直接把LaoWang定义成一个男人:
dim LaoWang as Male
运行一下就会发现,LaoWang = new Human("老王", "男", 177)这句话行不通了。因为LaoWang已经不是一个笼统的“人”,我们要改成:
LaoWang = new Male("老王", "男", 177)
但是Male没有带参数的构造函数,我们就要加上去:
sub New(Byval Name as string, byval Gender as String, byval Stature as integer)
MyBase.New(Name, "男", Stature)
end sub
这里MyBase.New是调用Human的构造函数来构造自己。这里可以直接把参数传过去。而且不管传过来的Gender是什么,我们一律将其改为“男”。
男人和女人的区别在哪里呢?就是男人不能生小孩。所以我们可以在Male类中把Human里的Born函数重写一下,使其更适合Male。不过在这之前,我们要把Human中的Born函数加上一个修饰符overridable(可重写的):
public overridable function Born() as Human
if Gender = "女" then
return new Human("","",50)
else
return nothing
end if
end function
然后我们在Male中重写Born函数。这里不用判断性别了,因为是在Male里头:
public overrides function Born() as Human
Console.WriteLine("我使劲生,但就是生不出来啊~~")
return nothing
end function
好了,下面是完整的演示代码。至于Female呢,你自己试着去写写看:
imports System
public module MyModule
sub Main
dim LaoWang as Male
LaoWang = new Male("老王", "男", 177)
AddHandler LaoWang.FallIll, AddressOf GoToHospital
Console.writeline("{0}, {1}, 身高{2}厘米", _
LaoWang.Name, LaoWang.Gender, LaoWang.Stature)
LaoWang.Born()
LaoWang.Eat() '这里引发事件
Console.Read
end sub
sub GoToHospital(Byval Name as String)
dim s as string
s = Name & "被送到医院去了。"
Console.WriteLine(s)
end sub
end module
public class Human
public Name as String
public Gender as String
public Stature as integer
sub New(Byval Name as string, byval Gender as String, byval Stature as integer)
me.Name = Name
me.Gender = Gender
me.Stature = Stature
end sub
sub New() '不带参数的构造函数
end sub
public event FallIll(Byval Name as String)
public sub Eat()
raiseevent FallIll(me.Name)
end sub
public sub Sleep()
end sub
public sub SeeADoctor()
end sub
public overridable function Born() as Human
if Gender = "女" then
return new Human("","",50)
else
return nothing
end if
end function
end class
public class Male
inherits Human
sub New(Byval Name as string, byval Gender as String, byval Stature as integer)
MyBase.New(Name, "男", Stature)
end sub
public overrides function Born() as Human
Console.WriteLine("我使劲生,但就是生不出来啊~~")
return nothing
end function
end class
public class Female
inherits Human
end class
但是这个世界是很复杂的。比如四边形当中有矩形,也有等边四边形。正方形呢,同时具有矩形和等边四边形的性质,照理说应该可以同时从两者中继承,也就是多重继承。不过VB.net不允许这么做。具体原因嘛,我说不太清。总之多重继承还有一些逻辑上的东西没解决,除了C++之外好像还没有其他语言敢用。
本文地址:http://com.8s8s.com/it/it43066.htm