请问这样写可以吗?(以一个子类为示范)

来源:2-21 编程练习

Star3327752

2021-07-27 17:08:16

相关代码:

package Car;

public class NonMotor {
// 私有属性:品牌、颜色、轮子(默认2个)、座椅(默认 1个)
private String brand;
private String color;
private int wheel = 2;
private int chair = 1;

// 无参构造方法
public NonMotor() {

}

// 双参构造方法,完成对品牌和颜色的赋值
public NonMotor(String brand, String color) {
this.setBrand(brand);
this.setColor(color);
}

// 四参构造方法,分别对所有属性赋值
/**
* @param brand
* @param color
* @param wheel
* @param chair
*/
public NonMotor(String brand, String color, int wheel, int chair) {
this.setBrand(brand);
this.setChair(chair);
this.setColor(color);
this.setWheel(wheel);
}

// 公有的get***/set***方法完成属性封装
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 getChair() {
return chair;
}

public void setChair(int chair) {
this.chair = chair;
}

// 方法:运行,描述内容为:这是一辆**颜色的,**牌的非机动车,有**个轮子,有**个座椅的非机动车。其中**的数据由属性提供

public void notice() {
System.out.println("这是一辆"+this.getColor()+"颜色的,"+this.getBrand()+"牌的非机动车,有"+this.getWheel()+"个轮子,有"+this.getChair()+"个座椅的非机动车");
}
}

相关代码:

​package Car;

public class Bicycle extends NonMotor {

public Bicycle() {

}

public Bicycle(String brand,String color) {
this.setBrand(brand);
this.setColor(color);

}
public void notice() {
System.out.println("这是一辆"+this.getColor()+"颜色的自行车,车品牌为:"+this.getBrand());
}
}

相关代码:

package Car;

public class Test {

public static void main(String[] args) {
NonMotor sc=new NonMotor("星环","红色");
sc.notice();
Bicycle sr=new Bicycle("星星","黄色");
sr.notice();


}

}


写回答

1回答

好帮手慕小小

2021-07-27

同学你好,代码实现是可以的,很好,继续加油!

祝学习愉快~

0

0 学习 · 9886 问题

查看课程