重载构造方法的问题
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("白头叶猴","头上有白毛,喜欢吃树叶"); } }
为什么出来的结果是
我是使用无参构造产生的猴子
名称长尾猴
特征尾巴长
我是使用有参构造产生的猴子
名称:长尾猴
特征:尾巴长
我"白头叶猴","头上有白毛,喜欢吃树叶"没有赋值给有参构造方法
正在回答
因为你创建one这个monkey实例时,用的是无参构造方法,这时已经赋值是长尾猴,尾巴长了。
调用one.xianshi();时应该没有问题,按照方法内所写语句,会显示"我是使用无参构造产生的猴子",然后照刚刚一开始的赋值显示。
但是你再直接调用one.xianshi("白头叶猴","头上有白毛,喜欢吃树叶");并不会有从新赋值的效用,因为这个方法里也没有重新赋值,只是印出目前有的值,因为用了this.name和this.feature,this代表此对象
除非你写this.name = name; 和this.feature = feature;才会赋值,但这也不是"赋值给有参构造方法",而是直接赋值给这两个属性。
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);
}
- 参与学习 人
- 提交作业 5461 份
- 解答问题 7235 个
此次推出的专题为Android攻城狮培养计划的第一部分语法与界面基础篇,将带大家从0开始学习Android开发。
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星