我想执行一些通用代码并初始化许多类共有的变量。在基类中完成所有这些工作是有意义的。然后,根据创建的数据,我想执行一些特定于特定功能的代码。我觉得这些函数应该在从基类派生的类中。但是,我也希望能够访问在基类中初始化的数据。
像这样的东西:
class Animal
{
public Animal()
{
public int _earCount = 2;
// determine if the planet is all water or all land
}
}
class Dog : Animal
{
public WagEars()
{
// for each ear, execute code to wag it
}
}
class Whale : Animal
{
public FlipTail()
{
// code to flip
}
}
public main()
{
Animal fred = new Animal;
// what code goes here to invoke WagEars if the planet is all land?
}
本质上,我要做的是为所有对象执行通用的页眉/页脚类型代码,中间有一些特定于派生类的代码。
创建 fred 时,直到执行公共代码后,我才知道它是狗还是鲸鱼。