编程练习:某公司要开发“XX车行管理系统”,请使用面向对象的思想,设计自定义类描述自行车、电动车和三轮车。
程序参考运行效果图如下:
任务
任务分析;
第一步:分析自行车、电动车和三轮车的共性:
- 都是非机动车,具有非机动车的基本特征
- 都有运行的方法
第二步:根据共性,定义非机动车
属性:品牌、颜色、轮子(默认2个)、座椅(默认 1个)
方法:
1. 编写无参构造方法、双参构造方法和四参构造方法,其中,在双参构造方法中,完成对品牌和颜色的赋值;在四参构造方法中,完成所有属性的赋值
2. 编写运行的方法,描述内容为:这是一辆**颜色的,**牌的非机动车,有**个轮子,有**个座椅的非机动车。其中**的数据由属性提供
第三步:定义自行车、电动车和三轮车分别继承自行车类,要求:
- 自行车类:
- 在构造方法中调用父类多参构造,完成属性赋值
- 重写运行方法,描述内容为:这是一辆**颜色的,**牌的自行车。其中**的数据由属性提供
- 电动车:
- 增加“电池品牌”属性
- 重写运行方法,描述内容为:这是一辆使用**牌电池的电动车。其中**的数据由属性提供
- 三轮车:
- 在无参构造中实现对轮子属性值进行修改
- 重写运行方法,描述内容为:三轮车是一款有**个轮子的非机动车。其中**的数据由属性提供
父类
package com.proj.car;
public class father {
// 父类信息
private String color;// 颜色
private String feiji;// 非机动车
private int lunzi;// 轮子
private int zuoyi;// 座椅
// 无参构造
public father() {
}
// 双参有参构造
public father(String color, String feiji) {
this.setColor(color);
this.setFeiji(feiji);
}
// 四参有参构造
public father(String color, String feiji, int lunzi, int zuoyi) {
this.color = color;
this.feiji = feiji;
this.lunzi = lunzi;
this.zuoyi = zuoyi;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getFeiji() {
return feiji;
}
public void setFeiji(String feiji) {
this.feiji = feiji;
}
public int getLunzi() {
return lunzi;
}
public void setLunzi(int lunzi) {
this.lunzi = lunzi;
}
public int getZuoyi() {
return zuoyi;
}
public void setZuoyi(int zuoyi) {
this.zuoyi = zuoyi;
}
public String lianjie() {
String str = "";
System.out.println("父类信息测试:"+"这是一辆" + this.color + "颜色的," + this.feiji + "的非机动车,有" + this.lunzi + "个轮子,有"
+ this.zuoyi + "个座椅");
return str;
}
}
自行车类
package com.proj.car;
public class son extends father {
public son () {
super();
}
public son(String color,String pinpai) {
super(color,pinpai);
System.out.println("自行车类信息测试:这是一辆"+color+"的,"+pinpai+"的自行车");
}
}
电动车类
package com.proj.car;
public class son1 extends father {
//添加电池品牌属性
private String dianchi;
public String getDianchi() {
return dianchi;
}
public void setDianchi(String dianchi) {
this.dianchi = dianchi;
}
public son1 () {
super();
}
public son1 (String dianchi) {
super();
this.dianchi = dianchi;
System.out.println("电动车类信息测试:这是一辆使用" + this.getDianchi() + "牌电池的电动车。");
}
}
三轮车类
package com.proj.car;
public class sanlunche extends father{
public sanlunche(int n) {
super();
this.setLunzi(n);
}
public String neirong() {
String str="三轮车类信息测试:三轮车是一款有" + this.getLunzi()+"个轮子的非机动车";
return str;
}
}
测试:
package com.proj.test;
import com.proj.car.father;
import com.proj.car.sanlunche;
import com.proj.car.son;
import com.proj.car.son1;
public class Sontest {
public static void main(String[] args) {
father one = new father("红色","天宇牌",4,2);
one.lianjie();
son zixingche = new son("黄色","捷安特牌");
son1 diandongche = new son1("飞鹤");
sanlunche san = new sanlunche(3);
System.out.println(san.neirong());
}
}