请问是这个实现思路吗
来源:2-21 编程练习
赵林0225
2021-07-08 10:53:38
public class NonMotor {
/*此类为父类-非机动车类
* 属性为:品牌、颜色、轮子(默认两个)、座椅(默认一个)
*/
private String brand;//品牌
private String color;//颜色
private int wheel=2;//轮子,默认两个
private int seat=1;//座椅,默认一个
//添加无参构造
public NonMotor() {
}
//添加双参构造,对品牌和颜色进行赋值
public NonMotor(String brand,String color) {
this.setBrand(brand);
this.setColor(color);
}
//添加全参构造,对所有属性进行赋值
public NonMotor(String brand,String color,int wheel,int seat) {
this.setBrand(brand);
this.setColor(color);
this.setSeat(seat);
this.setWheel(wheel);
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
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 work() {
String str = "这是一辆"+this.color+"颜色的,"+this.brand+"的非机动车,有"+this.wheel+"个轮子,有"+this.seat+"个座位的非机动车";
return str;
}
相关代码:
public class Bicycle extends NonMotor{
//添加构造方法,通过super调用父类的双参构造,完成颜色和品牌的属性赋值
public Bicycle() {
super("捷安特牌","黄颜色");
}
//重写父类work方法
public String work(){
String str="这是一辆"+this.getColor()+"的,"+this.getBrand()+"的自行车。";
return str;
}
相关代码:
public class ElectricVehicle extends NonMotor{
//增加了电池品牌的属性
private String battery;
//添加无参构造
public ElectricVehicle() {
}
//添加全参构造方法
public ElectricVehicle(String battery) {
this.battery=battery;
}
//get\set方法添加
public String getBattery() {
return battery;
}
public void setBattery(String battery) {
this.battery = battery;
}
//重写方法
public String work() {
String str="这是一辆使用"+this.battery+"电池的电动车";
return str;
}
相关代码:
public class Tricycle extends NonMotor{
//添加无参构造
public Tricycle() {
super.setWheel(3);
}
//重写方法
public String work() {
String str="三轮车是一款有"+this.getWheel()+"个轮子的非机动车";
return str;
}
相关代码:
public class test {
public static void main(String[] args) {
System.out.print("父类信息测试:");
NonMotor non=new NonMotor("红颜色","天宇牌",4,2);
System.out.println(non.work());
System.out.print("自行车类信息测试:");
Bicycle bicycle=new Bicycle();
System.out.println(bicycle.work());
System.out.print("电动车类信息测试:");
ElectricVehicle el=new ElectricVehicle("飞鸽牌");
System.out.println(el.work());
System.out.print("三轮车类信息测试:");
Tricycle tr=new Tricycle();
System.out.println(tr.work());
}
1回答
同学你好,代码整体完成的不错,比较符合题目要求,但还存在两个小问题,如下:
1、代码中在自行车类的无参构造中对属性进行了初始化,建议在自行车类中添加双参构造,完成对品牌颜色属性赋值,再在测试类中通过双参构造创建自行车类的对象:


2、类名命名采用帕斯卡命名法,如test应修改为Test。
祝学习愉快~
相似问题