示例代碼如下:
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調用其他構造方法必須寫在第一行。另外,一個類中兩個調用方法不能互相調用