一般来说,面向对象语言中的类之间有两种关系,允许一个类访问另一个类的特性:
- 继承,和
- 客户-供应商关系。
在第一种情况下,类继承了父类的所有特性,并且可以将它们称为自己的:
class APPLICATION
inherit
BLUE
rename
-- Class `APPLICATION' has `make' as well,
-- so the inherited one has to be renamed to avoid a clash.
make as make_blue
end
create
make
feature {NONE} -- Initialization
make
-- Run application.
do
-- This prints "test".
print ("test")
-- Call the inherited feature `{BLUE}.test'
-- renamed above into `make_blue'
-- that prints "writetest".
make_blue
end
end
在继承的情况下,调用是在同一个对象上执行的。
在客户-供应商关系中,调用是在不同的对象上执行的。在您的示例中,要调用的功能与创建过程一致,因此该调用成为正在创建的对象的创建指令的一部分:
class APPLICATION
create
make
feature {NONE} -- Initialization
make
-- Run application.
local
other: BLUE
do
-- This prints "test".
print ("test")
-- Create an object of type `BLUE'
-- calling its creation procedure `make'
-- that prints "writetest".
create other.make
end
end
关于何时使用一种方法而不是另一种方法的粗略近似如下。我们可以将继承视为“is-a”,将客户-供应商视为“has”关系。例如,一个苹果有一种颜色,但它不是一种颜色,因此客户-供应商关系更适合。另一方面,它是果实,所以继承关系更适合。在后一种情况下,苹果类通过指定一些其他属性(如形状和种子位置)来改进水果类。但它不能细化颜色类。与您的示例相同:它看起来不像APPLICATION
是 的示例BLUE
,因此客户-供应商关系似乎更合适。