Java中为解决变量的命名冲突和不确定性问题,引入关键字this代表其所在方
法的当前对象的引用:
1.this.property。举例说明带this关键字和不带this关键字的区别
不加this出现的情况:
public class ThisMethod { public static void main(String[] args) { MyDate myDate = new MyDate(); myDate.setDate(2020,9); myDate.PrintDate(); }}class MyDate { public int year; public int month; public void setDate(int year, int month) { year = year;//这里没有加this month = month;//这里没有加this } public void PrintDate() { System.out.println(year + "年 " + month + "月 "); }}
我们想要达到的预期结果是2020年9月。
而实际运行结果如下:
加上this之后才能达到我们的预期
public class ThisMethod { public static void main(String[] args) { MyDate myDate = new MyDate(); myDate.setDate(2020,9); myDate.PrintDate(); }}class MyDate { public int year; public int month; public void setDate(int year, int month) { this.year = year;//这里没有加this this.month = month;//这里没有加this } public void PrintDate() { System.out.println(year + "年 " + month + "月 "); }}
达到我们的预期:
2.this.method()举例说明
public class ThisMethod02 { public static void main(String[] args) { Student student = new Student(); student.name = "小小明"; student.doClass(); }}class Student { public String name; public void doClass() { System.out.println(name + "上课"); this.doHomeWork(); } public void doHomeWork() { System.out.println(name + "正在写作业"); }}
输出结果:
(3)this() 调用本类中其他构造方法
要注意以下几点:
public class ThisMethod03 { public static void main(String[] args) { Student01 student01 = new Student01(); student01.showMessage(); }}class Student01{ public String name; public int age; //无参构造方法 public Student01() { //小李解读: //1.this 放在首位 //2.只能在构造器中使用 //3.只能在构造器中调用另外一个构造器 //调用带有两个参数的构造器 this("张三",20); System.out.println("这是无参的构造器"); } public Student01(String name, int age) { this.name = name; this.age = age; System.out.println("这是带有两个参数的构造器"); } public void showMessage(){ System.out.println("姓名:"+name+",年龄:"+age); }}
输出结果:
留言与评论(共有 0 条评论) “” |