面向对象数据模型
继承和多态性
重要程度:10 分
<div>
<h2>1. 继承</h2>
<p>继承是一种允许子类或派生类从一个或多个父类或基类中继承属性和方法的机制。</p>
<ul>
<li><strong>概念:</strong>在面向对象数据模型中,继承允许一个类(子类)继承另一个类(父类)的特性,如属性和方法。</li>
<li><strong>优点:</strong>继承提高了代码的复用性和可维护性。</li>
</ul>
<h3>示例:</h3>
<pre>
<code>
// 定义一个父类 Animal
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
// 定义一个子类 Dog,继承自 Animal
class Dog extends Animal {
constructor(name, breed) {
super(name); // 调用父类的构造函数
this.breed = breed;
}
speak() {
console.log(`${this.name} barks.`);
}
}
// 创建一个 Dog 实例
let dog = new Dog('Rex', 'German Shepherd');
dog.speak(); // 输出 "Rex barks."
</code>
</pre>
</div>
<div>
<h2>2. 多态性</h2>
<p>多态性是指不同类的对象对同一消息做出响应的能力,即一个接口可以有多种实现方式。</p>
<ul>
<li><strong>概念:</strong>多态性使得一个函数或方法能够根据传入的对象类型执行不同的操作。</li>
<li><strong>优点:</strong>多态性增加了程序的灵活性和可扩展性。</li>
</ul>
<h3>示例:</h3>
<pre>
<code>
// 定义一个父类 Shape
class Shape {
area() {
throw new Error("Method not implemented.");
}
}
// 定义一个子类 Circle,继承自 Shape
class Circle extends Shape {
constructor(radius) {
super();
this.radius = radius;
}
area() {
return Math.PI * this.radius * this.radius;
}
}
// 定义一个子类 Rectangle,继承自 Shape
class Rectangle extends Shape {
constructor(width, height) {
super();
this.width = width;
this.height = height;
}
area() {
return this.width * this.height;
}
}
// 创建实例并调用 area 方法
let circle = new Circle(5);
let rectangle = new Rectangle(4, 6);
console.log(circle.area()); // 输出 "78.53981633974483"
console.log(rectangle.area()); // 输出 "24"
</code>
</pre>
</div>