this关键字

 1 public class Student {
 2     String name;
 3     int id;
 4     //无参构造方法
 5     public Student(){
 6         System.out.println("我是无参构造方法");
 7     }
 8     
 9     //有参的构造方法 可以调无参的构造方法  必须在第一行
10     public Student(String name){
11         //this();//this(id);报错 Cannot refer to an instance field id while explicitly invoking a constructor
12         //这里为啥报错呢?因为你的参数里面没有id
13         this.name=name;
14     }
15     public Student(int id){
16         //this();//this(name);这里为啥报错呢?因为你的参数里面没有name啊 大哥
17         this.id=id;
18     }
19     
20     public Student(String name,int id){
21         /*this();*/this(name);//this(id);
22         //这里因为有参数 name 和 id 所以 你可以调用其他2个构造方法(name,id)
23         //通过this调用其他构造方法! 构造器调用 必须在第一行
24         this.name=name;
25         this.id=id;
26         //this();报错 Constructor call must be the first statement in a constructor  构造方法调用 必须在第一行
27     }
28     
29     
30     public void setName(String name){
31         this.name=name;
32     }
33     public String getName(){
34         return name;
35     }
36     public void setId(){
37         this.id=id;
38     }
39     public int getId(){
40         return id;
41     }
42     
43     
44     public void study(){
45         name = "张三";
46         System.out.println(name+"在学习 ");
47     }
48     public void sayHello(String sname){
49         System.out.println(name+"向"+sname+"说:你好");
50     }
51 }
原文地址:https://www.cnblogs.com/PoeticalJustice/p/7608633.html