重载构造方法的问题

重载构造方法的问题

package Button;

public class Monkey {
    String name;
    String feature;

    public Monkey() {

        name = "长尾猴";
        feature = "尾巴长";

    }

    public Monkey(String name, String feature) {
        this.name = name;
        this.feature = feature;

    }

    public void xianshi() {

        System.out.println("我是使用无参构造产生的猴子");
        System.out.println("名称" + name);
        System.out.println("特征" + feature);
    }

    public void xianshi(String name, String feature) {

        System.out.println("我是使用有参构造产生的猴子");
        System.out.println("名称:" + this.name);
        System.out.println("特征:" + this.feature);
    }
}

package Button;

public class MonkeyTest {
      public static void main(String[] args){
          
           Monkey one =new Monkey();
           one.xianshi();
           one.xianshi("白头叶猴","头上有白毛,喜欢吃树叶");
          
      }
         
}

为什么出来的结果是

我是使用无参构造产生的猴子
名称长尾猴
特征尾巴长
我是使用有参构造产生的猴子
名称:长尾猴
特征:尾巴长
我"白头叶猴","头上有白毛,喜欢吃树叶"没有赋值给有参构造方法

正在回答

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

2回答

因为你创建one这个monkey实例时,用的是无参构造方法,这时已经赋值是长尾猴,尾巴长了。

调用one.xianshi();时应该没有问题,按照方法内所写语句,会显示"我是使用无参构造产生的猴子",然后照刚刚一开始的赋值显示。

但是你再直接调用one.xianshi("白头叶猴","头上有白毛,喜欢吃树叶");并不会有从新赋值的效用,因为这个方法里也没有重新赋值,只是印出目前有的值,因为用了this.name和this.feature,this代表此对象

除非你写this.name = name; 和this.feature = feature;才会赋值,但这也不是"赋值给有参构造方法",而是直接赋值给这两个属性。

  • 路总在笑 提问者 #1
    我在xianshi1方法里写this.name = name; this.feature = feature;他的控制台输出结果为 我是使用无参构造产生的猴子 名称null 特征null 我是使用有参构造产生的猴子 名称:null 特征:null 都是空的值呀 那我要怎么赋值给有参构造方法呢
    2017-03-17 14:00:25
  • TDYu #2
    你有动其他部分吗?没有的话应该要至少是长毛猴才对。 要赋值给"有参构造方法"就是new的时候直接写new Monkey("白头叶猴", "头上有白毛,喜欢吃树叶")这样
    2017-03-17 14:15:07
  • TDYu #3
    更正:至少是长"尾"猴
    2017-03-17 14:16:58
qq_秦皇岛崔哥_03852186 2017-04-10 14:58:48

public class Test {


public static void main(String[] args) {


// 调用无参构造方法实例对象


Monkey tow = new Monkey();

// 打印输出对象属性

tow.name = "长尾猴";

tow.feature = "尾巴长";


System.out.println("名称:" + tow.name);

System.out.println("特征:" + tow.feature);

System.out.println("--------------------------");

new Monkey("白头叶猴", "头上有白毛,喜欢吃树叶");

public class Monkey {

String name;

String feature;


// 无参的构造方法(默认初始化name和feature的属性值,属性值参考效果图)

Monkey() {

System.out.println("我是无参构造产生的猴子:");


}


// 带参的构造方法(接收外部传入的参数,分别向 name 和 feature 赋值)

Monkey(String name, String feature) {

this.name = name;

this.feature = feature;

System.out.println("我是有参构造产生的猴子:");

System.out.println("名称:" + name);

System.out.println("特征:" + feature);

}

问题已解决,确定采纳
还有疑问,暂不采纳

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

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

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

在线咨询

领取优惠

免费试听

领取大纲

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