定义和使用
构造方法的定义方式为:修饰符(常为public) 类名(参数列表){方法体};
在类创建实例化对象时,就是调用的构造方法;
如果没有手动写构造方法,会使用继承自Object类的构造方法,因此不写构造方法也可创建对象;
但是如果自己创建了构造方法(一个或多个,有参或无参),系统将不再提供默认的无参构造方法;
public class Test1{
public Test1(){
System.out.println("构造方法运行,对象已创建");
}
public static void main(String[] args){
Test1 t=new Test1();//本行运行结束后,控制台会输出"构造方法运行,对象已创建"
}
}
public class Test2{
public Test2(int num){}
public static void main(String[] args){
Test2 t=new Test2();//编译报错,因为自行定义了带参构造,系统不再提供无参构造,无法空参创建对象
}
}
public class Test3{
private int age;
private String name;
public Test3(){}
public Test3(int age){
this.age=age;
}
public Test3(String name){
this.name=name;
}
public Test3(String name,int age){
this.name=name;
this.age=age;
}
public static void main(String[] args){
//构造方法可以重载,以下四个对象都能成功创建
Test3 t1=new Test3();
Test3 t2=new Test3(12);
Test3 t3=new Test3("小强");
Test3 t4=new Test3("小强",12);
}
}
this关键字
this关键字表示本类的,可以通过this.属性名表示本类的属性,通过this,方法名()的方式调用本类方法(用处不大),this()的方式调用本类构造方法;
使用this()调用本类构造方法时要注意,this()语句只能位于构造方法的第一行,不能位于普通方法或者主方法,且只能位于第一行(限制了只能调用一次,因为调用多次必然只有一个位于第一行,this();中分号写上就算一行结束,this();this();算两行),this();方法也不能用于调用的本方法内,因为构造方法不可以递归(递归开始之前没有退出条件的定义)。