在面向对象编程中一个最重要的概念就是继承。继承允许我们在另一个类,这使得它更容易创建和维护一个应用程序来定义一个类。这也提供了一个机会重用代码的功能和快速的实施时间。
当创建一个类,而不是完全写入新的数据成员和成员函数,程序员可以指定新的类要继承现有类的成员。这个现有的类称为基类,新类称为派生类。
继承的想法实现是有关系的。例如,哺乳动物IS-A动物,狗,哺乳动物,因此狗IS-A动物,等等。
一个类可以从多个类中派生的,这意味着它可以继承数据和函数从多个基类。要定义一个派生类中,我们使用一个类派生列表中指定的基类(ES)。一个类派生列表名称的一个或多个基类和具有形式:
class derived-class: base-class
考虑一个基类Shape和它的派生类Rectangle,如下所示:
import std.stdio; |
// Base class |
class Shape |
{ |
public: |
void setWidth(int w) |
{ |
width = w; |
} |
void setHeight(int h) |
{ |
height = h; |
} |
protected: |
int width; |
int height; |
} |
// Derived class |
class Rectangle: Shape |
{ |
public: |
int getArea() |
{ |
return (width * height); |
} |
} |
void main() |
{ |
Rectangle Rect = new Rectangle(); |
Rect.setWidth(5); |
Rect.setHeight(7); |
// Print the area of the object. |
writeln("Total area: ", Rect.getArea()); |
} |
Total area: 35
派生类可以访问它的基类的所有非私有成员。因此,基类成员,不应该访问的派生类的成员函数应在基类中声明为private。
派生类继承了所有基类方法有以下例外:
构造函数,析构函数和基类的拷贝构造函数。
基类的重载运算符。
继承可以是多级的,如下面的例子。
import std.stdio; |
// Base class |
class Shape |
{ |
public: |
void setWidth(int w) |
{ |
width = w; |
} |
void setHeight(int h) |
{ |
height = h; |
} |
protected: |
int width; |
int height; |
} |
// Derived class |
class Rectangle: Shape |
{ |
public: |
int getArea() |
{ |
return (width * height); |
} |
} |
class Square: Rectangle |
{ |
this(int side) |
{ |
this.setWidth(side); |
this.setHeight(side); |
} |
} |
void main() |
{ |
Square square = new Square(13); |
// Print the area of the object. |
writeln("Total area: ", square.getArea()); |
} |
Total area: 169