请问这么写可以吗
来源:2-21 编程练习
Superdogso
2021-08-02 11:24:28
public class Test {
public static void main(String[] args) {
System.out.print("父类信息测试:");
NonMotor nonMotor = new NonMotor("天宇牌","红",4,2);
System.out.println(nonMotor.work());
System.out.print("自行车类信息测试:");
Bicycle bicycle = new Bicycle("捷安特","黄",2,1);
System.out.println(bicycle.work());
System.out.print("电动车类信息测试:");
ElectricVehicle electricVehicle = new ElectricVehicle("捷安特","黄",2,1,"" +
"飞鸽牌");
System.out.println(electricVehicle.work());
System.out.print("三轮车类信息测试:");
Tricycle tricycle = new Tricycle();
System.out.println(tricycle.work());
}
}
public class NonMotor {
// 私有属性:品牌、颜色、轮子(默认2个)、座椅(默认 1个)
private String bond;
private String color;
private int chile = 2;
private int chair =1;
// 无参构造方法
public NonMotor(){
}
// 双参构造方法,完成对品牌和颜色的赋值
public NonMotor(String bond,String color){
this.setColor(color);
this.setBond(bond);
}
// 四参构造方法,分别对所有属性赋值
public NonMotor(String bond, String color, int chile, int chair) {
this.setChair(chair);
this.setBond(bond);
this.setColor(color);
this.setChile(chile);
}
// 公有的get***/set***方法完成属性封装
public String getBond() {
return bond;
}
public void setBond(String bond) {
this.bond = bond;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getChile() {
return chile;
}
public void setChile(int chile) {
this.chile = chile;
}
public int getChair() {
return chair;
}
public void setChair(int chair) {
this.chair = chair;
}
// 方法:运行,描述内容为:这是一辆**颜色的,**牌的非机动车,有**个轮子,有**个座椅的非机动车。其中**的数据由属性提供
public String work() {
String str = "这是一辆"+this.getColor()+"颜色的,"+this.getBond()+"牌的非机动车,有"+this.getChile()
+"个轮子,有"+this.getChair()+"个座椅的非机动车。";
return str;
}
}
public class Bicycle extends NonMotor {
// 在构造方法中调用父类多参构造,完成属性赋值
public Bicycle(){
}
public Bicycle(String bond, String color, int chile, int chair) {
super(bond, color, chile, chair);
}
// 重写运行方法,描述内容为:这是一辆**颜色的,**牌的自行车。其中**的数据由属性提供
public String work() {
String a = "这是一辆"+this.getColor()+"颜色的,"+this.getBond()+"牌的自行车。";
return a;
}
}
public class ElectricVehicle extends NonMotor {
// 私有属性:电池品牌
private String elebond;
public ElectricVehicle(){
}
public ElectricVehicle(String bond, String color, int chile, int chair,String elebond) {
super(bond, color, chile, chair);
this.setElebond(elebond);
}
// 公有的get***/set***方法完成属性封装
public String getElebond() {
return elebond;
}
public void setElebond(String elebond) {
this.elebond = elebond;
}
// 重写运行方法,描述内容为:这是一辆使用**牌电池的电动车。其中**的数据由属性提供
public String work() {
String b = "这是一辆使用"+this.getElebond()+"牌电池的电动车。";
return b;
}
}
public class Tricycle extends NonMotor {
// 在无参构造中实现对轮子属性值进行修改
public Tricycle(){
super.setChile(3);
}
// 重写运行方法,描述内容为:三轮车是一款有**个轮子的非机动车。其中**的数据由属性提供
@Override
public String work() {
String c = "三轮车是一款有"+this.getChile()+"个轮子的非机动车。";
return c;
}
}
1回答
同学你好,代码实现是正确的,继续加油!
祝学习愉快~
相似问题