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就可以通过了 这是为什么啊?
{
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就可以通过了 这是为什么啊?
{
test(p,q); // 这里如果想调用构造函数应该用this(p,q)
c=r; // 现在相当于在调函数,所以加void把test变成
d=s; // 函数以后也可以运行
}
构造函数是jvm调用的吗?
别的地方只能用this?
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)