请大虾指导关于java的构造方法相关!!~~

来源:百度知道 编辑:UC知道 时间:2024/05/10 09:00:08
class Garbage
{
int index;
static int count;
Garbage()
{
count++;
System.out.println("Object "+count+" coustruct");
setID(count);
}
void setID(int id)
{
index=id;
}

每个类可以有零个或多个构造方法.构造方法是初始化一个类的对象时候调用的,它没有返回值,而且名字必须与类的名字一样,而成员函数是由类对象主动调用的,使用点操作符,它有返回值 构造方法只有在建立对象时由系统调用的,其他任何时候你都别指望用 当你没写构造方法编译器会为你添加一个默认的无参的构造方法
建议你去看看java的基础部分

class Garbage
{
int index;
static int count;
Garbage()
{
count++;
System.out.println("Object "+count+" coustruct");
setID(count);
}
void setID(int id)
{
index=id;
}
public static void main(String[] args)
{
/*new Garbage();
new Garbage();
new Garbage();
new Garbage();*/
Garbage it1=new Garbage();
Garbage it2=new Garbage();
Garbage it3=new Garbage();
Garbage it4=new Garbage();
//*it1.Garbage();
//*it2.Garbage();
//*it3.Garbage();
//*it4.Garbage();
}
}

就是这么规定的,规定就是规定。
其实是 编译器在编译的时候,发现你要这么做,就禁止你这么做了。
纯粹是由于::语言就是这么设计的。