this关键字
来源:互联网 发布:宾得k3ii知乎 编辑:程序博客网 时间:2024/06/06 09:34
使用场景1
public class person {private int age;private String name;void judge(int a){if(a>=0&&a<=100){age=a;}else System.out.println("输入的年龄数据有误");}void speak(){System.out.println(name+":"+age+"岁");}person(String name){ //这是一个构造函数this.name=name;}person(int age,String name){this.age=age;this.name=name;}}public class personDemo {public static void main(String[] arge){person a=new person(22,"起个名字好难");a.speak();}}
如程序所示,this.age代表这个对象的age,可以避免因为重名导致两个age都为局部变量的age;
当成员变量和局部变量重名,可以用this来区分。
this:代表对象,当前对象,this就是所在函数中所属对象的引用。
简单说,哪个对象调用了this所在的函数,this就代表哪个对象。如上程序所示,new person(22,“张天麒")调用了this所在的person函数,故this代表person的成员变量,而非构造函数中的局部变量。
使用场景2
person(String name){ //这是一个构造函数this.name=name;}person(String name,int age){this(name);this.name=name;}
如程序所示,当下面那个构造函数调用上面那个构造函数时,可以直接this(name);
需要注意的是,对this的调用必须是构造函数的第一个语句,即对本例来说,不能先this.name=name再this(name);因为初始化的动作要先执行。
this的应用:只要在本类中用到了本类的对象,就要用this,只是在不重名的情况下往往可以省略。
阅读全文
0 0
- 关键字this
- this关键字
- this关键字
- this 关键字
- this 关键字
- this关键字
- this关键字
- this 关键字
- this 关键字
- this 关键字
- this关键字
- 关键字this
- 关键字this
- this 关键字
- this 关键字
- this关键字
- this关键字
- This关键字
- NOI2005 维护数列
- yeoman一键生成前端项目代码
- 更新hosts,sudo:无法解析主机,rcnscd: command not found
- Cookie类基本的使用
- upD79F8513A(NEC)或upD78F0511A(NEC)之串口0中断发送和接收数据
- this关键字
- C++ 学习笔记
- 算法竞赛入门经典学习笔记
- Java异常Error和Exception的区别
- 右键菜单栏添加notepad++选项
- LeetCode75 Sort Colors
- hdu1130 How Many Trees?(Catalan+高精)
- 数据结构|创建学生成绩的间接寻址(实验2.5)
- 数据结构-----队列总结