JS编程题:与面向对象相关的题1

题目描述

  • 打车时,可以打专车或者快车。任何车都有车牌号和名称。
  • 不同车价格不同,快车每公里1元,专车每公里2元。
  • 行程开始时,显示车辆信息
  • 行程结束时,显示打车金额(假定行程就5公里)

要求 1、画出UML类图;2、用ES6语法写出该示例


解答

JS编程题:与面向对象相关的题1_第1张图片
UML类图:
JS编程题:与面向对象相关的题1_第2张图片
代码:

class Car {
     
  constructor(name, number) {
     
    this.name = name;
    this.number = number;
  }

}

class FastCar extends Car {
     
  constructor(name, number) {
     
    super(name, number);
    this.price = 1;
  }
}

class SpecialCar extends Car {
     
  constructor(name, number) {
     
    super(name, number);
    this.price = 2;
  }
}

class Trip {
     
  constructor(distance, car) {
     
    this.distance = distance;
    this.car = car;
  }

  beginTrip() {
     
    console.log(`车辆名称:${
       this.car.name},车牌号码:${
       this.car.number}`);
  }

  endTrip() {
     
    console.log(`行程${
       this.distance}公里,价格${
       this.distance * this.car.price}`);
  }
}

测试:

//面试题1:车
let car1 = new FastCar('快车',111);
let trip1 = new Trip(5,car1);
trip1.beginTrip();
trip1.endTrip();

let car2 = new SpecialCar('专车',222);
let trip2 = new Trip(5,car2);
trip2.beginTrip();
trip2.endTrip();

结果:
JS编程题:与面向对象相关的题1_第3张图片

你可能感兴趣的:(题,js,ES6,uml类图)