aardio 实现封装继承多态

//Car 实现封装继承多态

import console


//父类
class Car{
    ctor(make, model, color, year) {//构造函数,用于初始化对象的属性
        this.make = make //制造商
        this.model = model //型号
        this.color = color //颜色
        this.year = year //年份

    }
    
    startEngine = function() {//方法:启动引擎
        ..console.log("引擎启动了!")
    }
    
    accelerate = function() {//方法:加速
        ..console.log("车辆加速了!")
    }
    
    brake = function() {//方法:刹车
        ..console.log("车辆刹车了!")
    }
    
    describe = function() {// 方法:描述车辆信息
        ..console.log("这是一辆 " + this.year + " 年的 " + this.make + ",其型号为 " + this.model + ",颜色为 " + this.color + ".")
    }
}

//基类
class BMW{
    ctor(model, color, year){
        this = ..Car("宝马", model, color, year);    //继承Car类
    }
}

myCar = BMW("X3", "红色", 2020)
myCar.describe()
myCar.startEngine()
myCar.accelerate()
myCar.brake()



//父类
class Person{
    ctor(name, age) {
        this.name = name
        this.age = age
    }

    sayHello = function() {
        ..console.log("大家好,我叫 " + this.name + ", 我今年 " + this.age + " 岁。")
    }
}

//基类
class Student{
    ctor(name, age, grade) {
        this = ..Person(name, age)
        this.grade = grade
    }

    study = function() {
        ..console.log(this.name + " 正在学习,他现在 " + this.grade + "年级。")
    }
}

student = Student("小明", 10, 5)
student.sayHello()
student.study()




//封装
class Animal{
    ctor(name) {
        this.name = name
    }

    eat = function() {
        ..console.log(this.name + " is eating.")
    }
}

//继承
class Carnivore{
    ctor(name) {
        this = ..Animal(name)
    }

    eat = function() {
        ..console.log(this.name + " is eating meat.")
    }
}

//多态
class Herbivore{
    ctor(name) {
        this = ..Animal(name)
    }

    eat = function() {
        ..console.log(this.name + " is eating plants.")
    }
}

var carnivore = Carnivore("Tiger")
var herbivore = Herbivore("Deer")
carnivore.eat()  // 输出 "Tiger is eating meat."
herbivore.eat()  // 输出 "Deer is eating plants."



console.pause(true)

 

posted @ 2024-05-26 18:40  Axuanup  阅读(40)  评论(0编辑  收藏  举报