aardio 實現封裝繼承多型

Axuanup發表於2024-05-26
//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)

相關文章