Java上机作业02
题目:
定义一个汽车类(Car),要求包含以下属性和方法:
属性:型号、车牌、时速
构造方法:有参数,通过参数传递设置属性的值。
成员方法:定义所有属性的getter、setter访问器;
定义方法驾驶drive(int m):传入参数时间m(分为单位),利用时速计算并返回行驶的距离。
定义方法print():输出汽车型号、车牌信息。
public class Car{
String type;
String no;
int speed;
public Car(String type,String no,int speed) {
this.type=type;
this.no=no;
this.speed=speed;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getNo() {
return no;
}
public void setNo(String no) {
this.no = no;
}
public int getSpeed() {
return speed;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public double drive(int m) {
return (this.speed/60.0)*m;
}
public void print() {
System.out.println("汽车型号:"+type+"车牌:"+no);
}
}
定义Car的子类Taxi(出租车):
新增属性:fare(每公里单价),startPrice(起步价)
定义构造方法:有参,调用父类的构造方法设置从父类继承的属性的值,设置新属性price、起步价的值。
新增成员方法pay(int m):传入参数时间m,调用父类的drive方法求出行驶的公里数,然后按以下公式计算并返回费用:(3公里以内为起步价) 费用=起步价+(里程数-3公里)*每公里单价
public class Taxi extends Car{
double fare;
double startPrice;
public Taxi(String type,String no,int speed,double fare,double startPrice) {
super(type,no,speed);
this.fare=fare;
this.startPrice=startPrice;
}
public double pay(int m) {
return startPrice+(drive(m)-3)*fare;
}
}
定义测试类CarDemo:编写main方法,在main方法中建立Taxi类对象,并调用其pay方法,传入时间计算某次打车的价钱,并把结果输出。
public class Cardemo {
public static void main(String[] args) {
Taxi taxi=new Taxi("劳斯莱斯","粤G888888",60,2.6,12);
double cost=taxi.pay(30);
taxi.print();
System.out.println("打车30分钟需要支付费用是:"+cost);
}
}