This 在构造函数中的固定用法

class Person{
  String name;
  int age;
  char gender;   
  public Person (String name){
     this.name = name;
  }  
   public Person (String name , int age){
     this.name = name;
     this.age = age;
  }
  public Person (String name , int age ,char gender){
     this.name = name;
     this.age = age;
     this.gender = gender;
  }  

  public void introduce(){
    System.out.println("我是"+name+"     今年"+age+"岁     性别: "+gender);
  }  
}

  

和下面的代码相同

class Person{
  String name;
  int age;
  char gender;   
  public Person (String name){
     this.name = name;
  }  
   public Person (String name , int age){
     this(name);//调用只有一个参数的构造函数(必须是此构造函数里的第一行)
     this.age = age;
  }
  public Person (String name , int age ,char gender){
     this(name,age);//调用有两个参数的构造函数(必须是此构造函数里的第一行)
this.gender = gender;
}
public void introduce(){
System.out.println("我是"+name+" 今年"+age+"岁 性别: "+gender);
}
}


  

 

posted on 2018-03-07 17:08  ★【金字塔】☆  阅读(308)  评论(0编辑  收藏  举报