码迷,mamicode.com
首页 > 编程语言 > 详细

Java之this关键字

时间:2020-01-09 00:57:49      阅读:74      评论:0      收藏:0      [点我收藏+]

标签:用法   注意   his   Speak   vat   参与   关键字   inf   super   

this关键字概述:

1.this关键字在方法内部使用,即这个方法所属对象的引用。

2.this关键字在构造器内部使用,表示该构造器正在初始化的对象。

3.this关键字可以调用类的属性、方法和构造器。

this关键字功能:

1.当在方法内需要用到调用该方法的对象时,就用this。

2.可以用this来区分属性和局部变量。比如:this.name = name;

 1 class Person{  //使用this,调用属性、方法
 2     private String name ;
 3     private int age ;
 4     public Person(String name ,int age){
 5         this.name = name ;
 6         this.age= age; }
 7     public void getInfo() {
 8         System.out.println("姓名: " + name);
 9         this.speak();
10     }
11     public void speak(){
12         System.out.println("年龄:"+ this .age);
13     }
14 }

this关键字用法

1.在任意方法或构造器内,如果使用当前类的成员变量或成员方法,

可以在其前面添加this,增强程序的阅读性,通常都习惯省略this。

2.当形参与成员变量同名时,如果在方法内或构造器内需要使用成员变量,

必须添加this来表明该变量是类的成员变量。

3.使用this访问属性和方法时,如果在本类中未找到,会从父类中查找。

4. this可以作为一个类中构造器相互调用的特殊格式。

 1 class Person {  //使用this调用本类的构造器
 2     private String name;
 3     private int age;
 4 
 5     public Person() {
 6         //无参构造器
 7         System.out.println("新对象实例化");
 8     }
 9 
10     public Person(String name) {
11         this(); //调用本类中的无参构造器
12         this.name = name;
13     }
14 
15     public Person(String name, int age) {
16         this(name);  //调用有一个参数的构造器
17         this.age = age;
18     }
19 
20     public String getInfo() {
21         return "姓名:" + name + ",年龄:" + age;
22     }
23 }    

 注意事项:

1.可以在类的构造器中使用"this(形参列表)"的方式,调用本类中重载的其他的构造器。

2.明确构造器中不能通过"this(形参列表)"的方式调用自身构造器。

3.如果一个类中声明了n个构造器,则最多有n- 1个构造器中使用了"this(形参列表)"。

4."this(形参列表)"必须声明在类的构造器的首行。

5.在类的一个构造器中,最多只能声明一个"this(形参列表)"。

this和super对比:

技术图片

Java之this关键字

标签:用法   注意   his   Speak   vat   参与   关键字   inf   super   

原文地址:https://www.cnblogs.com/ZengBlogs/p/12169049.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!