面向对象编程(八)——this关键字
很多人一提起它,就说“当前对象”,可到底什么是当前对象,是什么当前对象,他自己也不清楚。
this(隐式参数)
- 普通方法中,this总是指向当前调用该方法的对象。
- 构造方法中,this总是指向正要初始化(创建)的对象。
- this不能用于static方法。
【例1】
public class Student { //静态数据 String name; int id; //set方法 public void setName(String name) { this.name = name; } //构造方法 public Student(String name,int id){ this();//通过this调用其他构造方法,必须位于第一句! //Constructor call must be the first statement in a constructor // this(name); this.name=name; this.id=id; } public Student(String name){ this.name= name; } public Student(){ System.out.println("构造一个对象"); } //动态的行为 public void study(){ this.name="熊二";//this表示当前对象,在普通方法中,加与不加含义是一样的。 System.out.println(name+"在学习"); } public void sayHello(String sname){ System.out.println(name + "向" +sname +"说,你好~"); } }
【例2】
/** * 本示例为了说明this的三种用法! */ package test; public class ThisTest { private int i=0;
//第一个构造器:有一个int型形参 ThisTest(int i){ this.i=i+1;//此时this表示当前对象,this.i表示引用成员变量i,而非函数参数i System.out.println("Int constructor i——this.i: "+i+"——"+this.i); System.out.println("i-1:"+(i-1)+"this.i+1:"+(this.i+1)); //从两个输出结果充分证明了i和this.i是不一样的! }
// 第二个构造器:有一个String型形参 ThisTest(String s){ System.out.println("String constructor: "+s); }
// 第三个构造器:有一个int型形参和一个String型形参 ThisTest(int i,String s){ this(s);//this调用第二个构造器 //this(i); /*此处不能用,因为其他任何方法都不能调用构造器,只有构造方法能调用他。 但是必须注意:就算是构造方法调用构造器,也必须为于其第一行,构造方法也只能调 用一个且仅一次构造器!*/ this.i=i++;//this以引用该类的成员变量 System.out.println("Int constructor: "+i+"\n"+"String constructor: "+s); }
public ThisTest increment(){ this.i++; return this;//返回的是当前的对象,该对象属于(ThisTest) } public static void main(String[] args){ ThisTest tt0=new ThisTest(10); ThisTest tt1=new ThisTest("ok"); ThisTest tt2=new ThisTest(20,"ok again!"); System.out.println(tt0.increment().increment().increment().i); //tt0.increment()返回一个在tt0基础上i++的ThisTest对象, //接着又返回在上面返回的对象基础上i++的ThisTest对象! } }
运行结果:

Int constructor i——this.i: 10——11 i-1:9this.i+1:12 String constructor: ok String constructor: ok again! Int constructor: 21 String constructor: ok again! 14
分析:
细节问题注释已经写的比较清楚了,这里不在赘述,只是总结一下,其实this主要要三种用法:
1、表示对当前对象的引用! 2、表示用类的成员变量,而非函数参数,注意在函数参数和成员变量同名是进行区分!其实这是第一种用法的特例,比较常用,所以那出来强调一下。 3、用于在构造方法中引用满足指定参数类型的构造器(其实也就是构造方法)。但是这里必须非常注意:只能引用一个构造方法且必须位于第一位! 还有就是注意:this不能用在static方法中!所以甚至有人给static方法的定义就是:没有this的方法!虽然夸张,但是却充分说明this不能在static方法中使用! |
-------------我是低调的分割线--------------------------
如果对你有帮助,可以点击“推荐”哦`(*∩_∩*)′




分类:
①Java基础学习笔记
标签:
java基础
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?