有需要修改的吗
来源:2-23 编程练习
慕尼黑3476150
2019-10-15 21:08:42
public class test {
public static void main(String[] args) {
System.out.print("父类信息测试:");
NonMotor no=new NonMotor("红","天宇",4,2);
System.out.println(no.work());
System.out.print("自行车类信息测试:");
Bicycle bi=new Bicycle();
System.out.println(bi.work());
System.out.print("电动车类信息测试:");
ElectricVehicle el=new ElectricVehicle();
el.setDian("飞鸽");
System.out.println(el.work());
System.out.print("三轮车类信息测试:");
Tricycle tr=new Tricycle();
System.out.println(tr.work());
}
}
public class NonMotor {
// 私有属性:品牌、颜色、轮子(默认2个)、座椅(默认 1个)
private String pin;
private String yan;
private int lun;
private int zuo;
// 无参构造方法
public NonMotor() {
}
// 双参构造方法,完成对品牌和颜色的赋值
public NonMotor(String pin,String yan) {
this.setPin(pin);
this.setYan(yan);
}
// 四参构造方法,分别对所有属性赋值
public NonMotor(String pin,String yan,int lun,int zuo) {
this.setPin(pin);
this.setYan(yan);
this.setLun(lun);
this.setZuo(zuo);
}
// 公有的get***/set***方法完成属性封装
public String getPin() {
return pin;
}
public void setPin(String pin) {
this.pin = pin;
}
public String getYan() {
return yan;
}
public void setYan(String yan) {
this.yan = yan;
}
public int getLun() {
return lun;
}
public void setLun(int lun) {
this.lun = lun;
}
public int getZuo() {
return zuo;
}
public void setZuo(int zuo) {
this.zuo = zuo;
}
// 方法:运行,描述内容为:这是一辆**颜色的,**牌的非机动车,有**个轮子,有**个座椅的非机动车。其中**的数据由属性提供
public String work() {
String str="这是一辆"+this.getYan()+"颜色的,"+this.getPin()+"牌的非机动车,有"+this.getLun()
+"个轮子,有"+this.getZuo()+"个座椅的非机动车。";
return str;
}
}
public class Bicycle extends NonMotor {
// 在构造方法中调用父类多参构造,完成属性赋值
public Bicycle() {
super("黄","捷安特");
}
// 重写运行方法,描述内容为:这是一辆**颜色的,**牌的自行车。其中**的数据由属性提供
public String work() {
String str="这是一辆"+this.getYan()+"颜色的,"+this.getPin()+"牌的非机动车";
return str;
}
}
public class ElectricVehicle extends NonMotor {
// 私有属性:电池品牌
private String dian;
// 公有的get***/set***方法完成属性封装
public String getDian() {
return dian;
}
public void setDian(String dian) {
this.dian = dian;
}
// 重写运行方法,描述内容为:这是一辆使用**牌电池的电动车。其中**的数据由属性提供
public String work() {
String str = "这是一辆" + this.getDian() + "牌电池的电动车";
return str;
}
}
public class Tricycle extends NonMotor {
// 在无参构造中实现对轮子属性值进行修改
public Tricycle() {
super.setLun(3);;
}
// 重写运行方法,描述内容为:三轮车是一款有**个轮子的非机动车。其中**的数据由属性提供
public String work() {
String str="三轮车是一款有"+this.getLun()+"个轮子的非机动车。";
return str;
}
}
1回答
好帮手慕小尤
2019-10-16
同学你好,有几个小问题,如下所示:
1. 类名首字母应该大写,建议将test修改为Test。
2. Bicycle类中建议定义带参构造方法,在测试类中使用构造方法赋值。修改后代码如下:
Bicycle:

测试类:

3. ElectricVehicle类中创建无参和带参构造方法,在测试类中使用带参构造方法创建对象。修改后代码如下:
ElectricVehicle类:

测试类:
如果我的回答解决了你的疑惑,请采纳!祝学习愉快!
相似问题