请问老师 我这段代码 调用work 方法,输出的结果为什么是错误的?

请问老师 我这段代码 调用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());

}

}http://img1.sycdn.imooc.com//climg/5e68c5d1096fa9dc10000321.jpg

正在回答

登陆购买课程后可参与讨论,去登陆

2回答

同学你好,work()方法输出是正确的  之所以输出结果不正确,是因为在构造方法中赋值错误,导致颜色与品牌颠倒。按照同学的写法,也可以更改为如下这种即可:

http://img1.sycdn.imooc.com//climg/5e69ae43094e661106920202.jpg

如果我的回答解决了你的疑惑,请采纳,祝学习愉快~

  • 慕标3002004 提问者 #1
    老师,那您的意思是在给构造方法中赋值时,必须按照有参构造方法的顺序赋值,是吗?
    2020-03-12 19:14:30
  • 好帮手慕小脸 回复 提问者 慕标3002004 #2
    同学理解是正确的,祝学习愉快~
    2020-03-13 10:33:45
好帮手慕小脸 2020-03-11 19:31:35

同学你好,因为有参构造方法的顺序是品牌在前,颜色在后,具体修改如下:

http://img1.sycdn.imooc.com//climg/5e68cbfd0941561208700281.jpg

如果我的回答解决了你的疑惑,请采纳,祝学习愉快~

  • 提问者 慕标3002004 #1
    这个调用的不是one.work,下面这段吗?不是按照下面这段顺序吗? public String work() { String str="这是一辆"+this.getColour()+"颜色的,"+this.getBrand()+"牌的非机动车,有"+this.getWheel()+"个轮子,有"+this.getSeat()+"个座椅的非机动车。";
    2020-03-11 21:38:53
问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
请稍等 ...
意见反馈 帮助中心 APP下载
官方微信

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师