(java)构造方法的定义和特点;如果程序中有多个类时,如何确定源程序文件的名称
构造方法的定义:
构造方法是一种特殊的方法,它是一个与类同名且没有返回值类型的方法。对象的创建就是通过构造方法来完成,其功能主要是完成对象的初始化。当类实例化一个对象时会自动调用构造方法。构造方法和其他方法一样也可以重载。
构造方法的特点:
1. 构造函数的命名必须和类名完全相同;在java中普通函数可以和构造函数同名,但是必须带有返回值。
2. 构造函数的功能主要用于在类的对象创建时定义初始化的状态。它没有返回值,也不能用void来修饰。这就保证了它不仅什么也不用自动返回,而且根本不能有任何选择。
3. 构造函数不能被直接调用,必须通过new运算符在创建对象时才会自动调用;而一般的方法是在程序执行到它的时候被调用的。
4. 当定义一个类的时候,通常情况下都会显示该类的构造函数,并在函数中指定初始化的工作也可省略,不过Java编译器会提供一个默认的构造函数.此默认构造函数是不带参数的。而一般的方法不存在这一特点。
class HelloWorld//(Box)
{
static int length;
static int width;
static int heigth;
void setBox(int l,int w,int h)
{
int l1;
int w1;
int h1;
}
int volume(int a,int B,int c)
{
int s;
s=a*B*c;
return s;
}
public static void main(String args[]){
int S;
HelloWorld b=new HelloWorld();
b.length=1;
b.width=2;
b.heigth=4;
S= b.volume(length,width,heigth);
System.out.println(S);
}
}
Class BankAccount{
Int acciuntnumber;
Int leftmoney;
public double getleftmoney () { //查询余额
System.out.println(leftmoney);
}
public void savemoney(double money) { //存款
leftmoney+=money;
}
public void getmoney (double money){ //取款
leftmonney-=money;
}
public BankAccount (int number, double money){ //默认的构造方法,用来初始化变量
acciuntnumber =123456;
letfmoney=500;
}
public static void main(String args[]) {
BlankAccount ba=new BlankAccount(123456,500);
ba.savemoney(1000);
System.out.println("存入1000元后,您的余额为:"+ba.getleftmoney());
ba.getmoney(2000);
System.out.println("取款2000元后,您的余额为:"+ba.getleftmoney());
}
}
这两段代码很好的解释了构造方法的特点。