示例代码如下:
class Student7{
private String name;
private int age;
public Student7(){
System.out.println("调用了无参构造方法");
}
public Student7(String name,int age)
{
this();
this.name=name;
this.age=age;
}
public String read()
{
return"我是:"+name+",年龄:"+age;
}
}
public class This2 {
public static void main(String[] args) {
// this调用构造方法
Student7 stu=new Student7("张三",18);
System.out.println(stu.read());
}
}
这段代码中,定义了一个无参构造方法和一个有参构造方法。
在有参构造方法代码片段中
public Student7(String name,int age)
{
this();
this.name=name;
this.age=age;
}
通过this()语句调用了无参构造方法
this调用类的构造方法时,必须只能在构造方法里调用,不能在成员方法里调用。
在构造方法里,this调用其他构造方法必须写在第一行。另外,一个类中两个调用方法不能互相调用