构造方法:
1.说明:
构造方法就是在创建并初始化对象时自动调用的特殊方法。换句话说,构造方法的目的在于创建对象时,初始化成员变量。
2.规则:
(1)与类名相同;
(2)无返回类型,不能写void;
上代码
public class Gril{
String house;
String car;
String deposit;
Gril(){} //默认无参构造方法
Gril(String house,double deposit){ //房子 存款构造方法
this.house = house;
this.deposit = deposit;
}
Gril(String house,String car,double deposit) { //方法 车子 存款构造方法
this.house = house;
this.car =car;
this.deposit = deposit;
}
public void printInfo(){
System.out.println("房子:"+house+",车子:"+car+",存款:"+deposit);}
}
public class Test{
public static void main(String args[]){
Gril gf = new Gril();
gf.printInfo();
}}
通过上述代码
1.类的实例化具体过程
Gril gf = new Gril();
其实对象实例化语法
类名 对象名= new 类名 =》 类名 对象名 = new 构造方法();
2.构造方法的重载
(1)希望先得到包含默认值的对象,再使用具体值初始化。
Gril gf = new Gril(); gf.house = "二室一厅";
(2)创建对象时,直接初始化不同的参数
(3)一个构造方法直接使用this调用另一个重载的构造方法
Gril(String house,double deposit){}
Gril(String house,String car,double deposit){
this.(house,deposit);
this.car = car;
}
ps:可以使用Eclipse/Source/Generate Constructor Using Fields快捷创建构造方法。
3.this关键字
this.成员变量名=参数名,this.用来指向当前对象,这样一来几遍成员变量名和参数名重名也不会造成冲突。所以就是在成员变量名和参数名重名时,用this.来区分两者。退一步讲,不用this,使用不和成员变量名同名的参数名,也是可以的。比如house = h;
4.在有参构造方法存在的情况下,需要手动调用无参构造方法(需要无参构造的情况下)。