请问老师 我这段代码 调用work 方法,输出的结果为什么是错误的?
public class NonMotor {
// 私有属性:品牌、颜色、轮子(默认2个)、座椅(默认 1个)
private String brand;
private String colour;
private int wheel=2;
private int seat=1;
// 无参构造方法
public NonMotor(){
}
// 双参构造方法,完成对品牌和颜色的赋值
public NonMotor(String brand,String colour){
this.setBrand(brand);
this.setColour(colour);
}
// 四参构造方法,分别对所有属性赋值
public NonMotor(String brand,String colour,int wheel,int seat){
this.setBrand(brand);
this.setColour(colour);
this.setWheel(wheel);
this.setSeat(seat);
}
// 公有的get***/set***方法完成属性封装
public void setBrand(String brand){
this.brand=brand;
}
public String getBrand(){
return brand;
}
public void setColour(String colour){
this.colour=colour;
}
public String getColour(){
return colour;
}
public void setWheel(int wheel){
this.wheel=wheel;
}
public int getWheel(){
return wheel;
}
public void setSeat(int seat){
this.seat=seat;
}
public int getSeat(){
return seat;
}
// 方法:运行,描述内容为:这是一辆**颜色的,**牌的非机动车,有**个轮子,有**个座椅的非机动车。其中**的数据由属性提供
public String work() {
String str="这是一辆"+this.getColour()+"颜色的,"+this.getBrand()+"牌的非机动车,有"+this.getWheel()+"个轮子,有"+this.getSeat()+"个座椅的非机动车。";
return str;
}
}
public class Test {
public static void main(String[] args) {
NonMotor one=new NonMotor("红","天宇",4,2);
System.out.println("父类信息测试:"+one.work());
}
}
正在回答
同学你好,work()方法输出是正确的 之所以输出结果不正确,是因为在构造方法中赋值错误,导致颜色与品牌颠倒。按照同学的写法,也可以更改为如下这种即可:
如果我的回答解决了你的疑惑,请采纳,祝学习愉快~
- 参与学习 人
- 提交作业 3802 份
- 解答问题 11489 个
本阶段带你迈入Java世界,学习Java必备基础知识,基础语法、面向对象思想以及常用工具类的使用。
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星