aardio 继承与多态
面向对象编程中的继承与多态
今天开始学习面向对象编程的核心概念——继承与多态,发现这两个概念和现实生活的现象很像,学起来挺有意思的。
一、继承
1. 简单继承的实现
先试着写了一个父类Animal和子类Dog的例子,发现继承真的像"遗传"一样:
父类定义了动物的基本属性(名字)和行为(发声)
子类Dog不用重复写这些代码,直接通过..Animal(...)继承父类的功能
子类还能重写父类的方法,比如让狗发出"汪汪"声而不是通用的"发出声音"
// 定义父类Animal
class Animal {
ctor(name) {
this.name = name;
}
speak = function() {
return this.name + " makes a sound.";
}
}
// Dog类继承Animal
class Dog {
ctor(...) {
this = ..Animal(...); // 调用父类构造函数
}
// 重写speak方法
speak = function() {
return this.name + " barks.";
}
}
import console;
var myDog = Dog("Buddy");
console.log(myDog.speak()); // 输出:Buddy barks.
console.pause();
2. 多层继承的理解
又试了三层继承(Animal→Dog→Puppy),发现子类可以层层继承上层的所有功能:
Puppy不仅能用Animal的name属性,还能复用Dog的构造逻辑
只需要在Puppy里写自己特有的逻辑(比如"小狗轻轻叫")
import console;
class Animal {
ctor(name) {
this.name = name;
}
speak = function() {
return this.name + " makes a sound.";
}
}
class Dog {
ctor(...) {
this = ..Animal(...);
}
speak = function() {
return this.name + " barks.";
}
}
class Puppy {
ctor(...) {
this = ..Dog(...);
}
speak = function() {
return this.name + " puppy barks softly.";
}
}
var myPuppy = Puppy("Tommy");
console.log(myPuppy.speak()); // 输出:Tommy puppy barks softly.
console.pause();
登录后方可回帖