构造函数的问题

lizi02 2005-11-27 12:28:53
public class test
{
int a,b,c,d;
public test(int x,int y)
{
a=x;
b=y;
}

public test(int p,int q,int r,int s)
{
test(p,q);
c=r;
d=s;
}
public static void main(String args[])
{
test temp=new test(1,2,3,4);
System.out.println(temp.a+""+temp.b+""+temp.c+""+temp.d);
}
}

这个程序编译会出错
public test(int x,int y)
{
a=x;
b=y;
}
test这个地方
但是在test前面加个void就可以通过了 这是为什么啊?
...全文
158 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
Net_Soul 2005-11-27
  • 打赏
  • 举报
回复
public test(int p,int q,int r,int s)
{
test(p,q); // 这里如果想调用构造函数应该用this(p,q)
c=r; // 现在相当于在调函数,所以加void把test变成
d=s; // 函数以后也可以运行
}
niko7 2005-11-27
  • 打赏
  • 举报
回复
因为这是在同一个类的内部,运行时还是同一个实例,所以构造函数调用构造函数 就用
this(...) 。

别的地方就用 new test(1,2) 或者 new test(1,2,3,4) 了
就像你的
public static void main(String args[])
{
test temp=new test(1,2,3,4);//就像这里
System.out.println(temp.a+""+temp.b+""+temp.c+""+temp.d);
}

/////
如果在 test 的直接子类中,那么还可能用
super(1,2) 或者 super(1,2,3,4)
tramp73 2005-11-27
  • 打赏
  • 举报
回复
Net_Soul(网 魂) 正解
lizi02 2005-11-27
  • 打赏
  • 举报
回复
呵呵 我也是这么想的
构造函数是jvm调用的吗?
别的地方只能用this?

62,629

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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