请帮忙检查代码,谢谢~
来源:2-17 super关键字的使用(下)
慕少6083615
2020-04-16 11:52:27
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("捷安特","黄");
System.out.println(bicycle.work());
System.out.print("电动车类信息测试:");
ElectricVehicle electricVehicle=new ElectricVehicle("飞鸽");
System.out.println(electricVehicle.work());
System.out.print("三轮车类信息测试:");
Tricycle tricycle=new Tricycle();
System.out.println(tricycle.work());
}
}
public class NonMotor {
// 私有属性:品牌、颜色、轮子(默认2个)、座椅(默认 1个)
private String brand;
private String color;
private int wheelNum=2;
private int seatNum=1;
// 无参构造方法
public NonMotor(){
}
// 双参构造方法,完成对品牌和颜色的赋值
public NonMotor(String brand,String color){
this.setBrand(brand);
this.setColor(color);
}
// 四参构造方法,分别对所有属性赋值
public NonMotor(String brand,String color,int wheelNum,int seatNum){
this.setBrand(brand);
this.setColor(color);
this.setWheelNum(wheelNum);
this.setSeatNum(seatNum);
}
// 公有的get***/set***方法完成属性封装
public void setBrand(String brand){
this.brand=brand;
}
public String getBrand(){
return brand;
}
public void setColor(String color){
this.color=color;
}
public String getColor(){
return color;
}
public void setWheelNum(int wheelNum){
this.wheelNum=wheelNum;
}
public int getWheelNum(){
return wheelNum;
}
public void setSeatNum(int seatNum){
this.seatNum=seatNum;
}
public int getSeatNum(){
return seatNum;
}
// 方法:运行,描述内容为:这是一辆**颜色的,**牌的非机动车,有**个轮子,有**个座椅的非机动车。其中**的数据由属性提供
public String work() {
String str="这是一辆"+this.getColor()+"颜色的,"+this.getBrand()+"牌的非机动车,有"+this.getWheelNum()+"个轮子,有"+this.getSeatNum()+"个座椅";
return str;
}
}
public class Bicycle extends NonMotor {
// 在构造方法中调用父类多参构造,完成属性赋值
public Bicycle(String brand,String color){
super(brand,color);
}
// 重写运行方法,描述内容为:这是一辆**颜色的,**牌的自行车。其中**的数据由属性提供
public String work(){
String str="这是一辆"+this.getColor()+"颜色的,"+this.getBrand()+"牌的自行车";
return str;
}
}
public class ElectricVehicle extends NonMotor {
// 私有属性:电池品牌
private String batteryBrand;
public ElectricVehicle(String batteryBrand){
this.setBatteryBrand(batteryBrand);
}
// 公有的get***/set***方法完成属性封装
public void setBatteryBrand(String batteryBrand){
this.batteryBrand=batteryBrand;
}
public String getBatteryBrand(){
return batteryBrand;
}
// 重写运行方法,描述内容为:这是一辆使用**牌电池的电动车。其中**的数据由属性提供
public String work(){
String str="这是一辆使用"+this.getBatteryBrand()+"牌电池的电动车";
return str;
}
}
public class Tricycle extends NonMotor {
// 在无参构造中实现对轮子属性值进行修改
public Tricycle(){
super.setWheelNum(3);
}
// 重写运行方法,描述内容为:三轮车是一款有**个轮子的非机动车。其中**的数据由属性提供
public String work(){
String str="三轮车是一款有"+this.getWheelNum()+"个轮子的非机动车";
return str;
}
}1回答
同学你好,代码运行正确很棒,继续努力,加油!
如果我的回答解决了你的疑惑,请采纳,祝学习愉快~
相似问题
回答 1
回答 1
回答 1
回答 1
回答 1