编程练习:
- 某公司要开发“XX车行管理系统”,请使用面向对象的思想,设计自定义类描述自行车、电动车和三轮车。 程序参考运行效果图如下:
任务分析:
第一步:分析自行车、电动车和三轮车的共性:
(1)、都是非机动车,具有非机动车的基本特征
(2)、都有运行的方法
第二步:根据共性,定义非机动车
属性:品牌、颜色、轮子(默认2个)、座椅(默认 1个)
方法:
(1)、编写无参构造方法、双参构造方法和四参构造方法,其中,在双参构造方法中,完成对品牌和颜色的赋值;在四参构造方法中,完成对所有属性的赋值
(2)、编写运行的方法,描述内容为:这是一辆xx颜色的,xx牌的非机动车,有xx个轮子,有xx个座椅的非机动车。其中xx的数据由属性提供
第三步:定义自行车、电动车和三轮车分别继承自行车类,要求:
(1)、自行车类:
①.在构造方法中调用父类多参构造,完成属性赋值
②.重写运行方法,描述内容为:这是一辆xx颜色的,xx牌的自行车。其中xx的数据由属性提供
(2)、电动车:
①.增加“电池品牌”属性
②.重写运行方法,描述内容为:这是一辆使用xx牌电池的电动车。其中xx的数据由属性提供
(三)、三轮车:
①.在无参构造中实现对轮子属性值进行修改
②.重写运行方法,描述内容为:三轮车是一款有xx个轮子的非机动车。其中xx的数据由属性提供
代码:
父类
package com.dodoke.car;
public class Car {
// 成员属性:颜色、品牌、轮子、座椅
private String color;// 颜色
private String type;// 品牌
private int wheel;// 轮子
private int seat;// 座椅
// 无参构造方法
public Car() {
}
// 带参构造
public Car(String color, String type) {
this.setColor(color);
this.setType(type);
}
public Car(String color, String type, int wheel, int seat) {
this.setColor(color);
this.setType(type);
this.setWheel(wheel);
this.setSeat(seat);
}
// 每项的get和set
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getWheel() {
return wheel;
}
public void setWheel(int wheel) {
this.wheel = wheel;
}
public int getSeat() {
return seat;
}
public void setSeat(int seat) {
this.seat = seat;
}
// 父类信息
public String info() {
String str = "父类信息测试:这是一辆" + this.getColor() + "颜色的," + this.getType() + "牌的非机动车,有" + this.getWheel() + "个轮子,有"
+ this.getSeat() + "个座椅";
return str;
}
}
自行车
package com.dodoke.car;
public class Bike extends Car {
// 自行车
// 无参构造
public Bike() {
}
// 重写父类
public Bike(String color, String type) {
super(color, type);
System.out.println("自行车类信息测试:这是一辆" + color + <