构造函数如何调用

zhangshaolei1 2010-05-04 09:27:34
public class study {

private String s = new String("null");
private int petalCount = 0;

study(String ss) {

System.out.println(
"------------------------");
}
study(String s, int petals) {
this(petals);
//! this(s); // Can't call two!
this.s = s; // Another use of "this"
System.out.println("222222222222222222222---"+s);
}
study(int petals) {
petalCount = petals;
System.out.println(
"1111111111111111111111---"
+ petalCount);
}
study() {
this("hi", 47);
System.out.println(
"333333333333333333333333");
}

void print() {
//! this(11); // Not inside non-constructor!
System.out.println(
"petalCount = " + petalCount + " s = "+ s);
}





public static void main(String[] args)
{

study x = new study();
x.print();
}


为什么运行结果是:
1111111111111111111111---47
222222222222222222222---hi
333333333333333333333333
petalCount = 47 s = hi

这个构造为什么没有执行:study(String ss)
...全文
121 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
wing_fly 2010-05-04
  • 打赏
  • 举报
回复
没有调用这个构造方法,this("hi", 47)调用study(String s, int petals) 构造方法,this(petals)调用study(int petals)构造方法,没有调用到构造方法study(String ss)
wutian4567268 2010-05-04
  • 打赏
  • 举报
回复
你的流程是:
main(String[] args)
调用
study()
调用
study(String s, int petals)
调用
study(int petals)

打印1111111111111111111111
回到study(String s, int petals)
打印222222222222222222222
回到study()
打印333333333333

结束
zhangshaolei1 2010-05-04
  • 打赏
  • 举报
回复
我明白了,谢谢wutian4567268的回答。
zhangshaolei1 2010-05-04
  • 打赏
  • 举报
回复
你这样说的话那运行结果就应该是先打印333333333333了
wutian4567268 2010-05-04
  • 打赏
  • 举报
回复
study(String s, int petals) {
this(petals);
//! this(s); // Can't call two! 这里被注释掉了this.s = s; // Another use of "this"
System.out.println("222222222222222222222---"+s);
}
Mars_Ma_OK 2010-05-04
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 wutian4567268 的回复:]
你的流程是:
main(String[] args)
调用
study()
调用
study(String s, int petals)
调用
study(int petals)
结束
[/Quote]

up!
wutian4567268 2010-05-04
  • 打赏
  • 举报
回复
你的流程是:
main(String[] args)
调用
study()
调用
study(String s, int petals)
调用
study(int petals)
结束
zhangshaolei1 2010-05-04
  • 打赏
  • 举报
回复
为什么没有调用?而却调用了study(int petals)
meadking 2010-05-04
  • 打赏
  • 举报
回复
public static void main(String[] args)
{

study x = new study("输入构造参数,会执行");
x.print();
}
wutian4567268 2010-05-04
  • 打赏
  • 举报
回复
因为整个流程都没有调用study(String ss)

67,515

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧