• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

java中什么是this

java 搞代码 4年前 (2022-01-09) 12次浏览 已收录 0个评论

this关键字是什么?

关键字this只能在方法内部使用,表示对当前对象的引用。

this关键字的用法

1、访问成员变量,区分成员变量和局部变量

2、访问成员方法

3、访问构造方法

4、返回对当前对象的引用

5、将对当前对象的引用作为参数传递给其他方法

用法如下:Test0505.java

class Person{	private String name;//成员变量	private int age;	Person(){}	Person(<p style="color:transparent">本文来源gao!%daima.com搞$代*!码网1</p>String name){//局部变量		this.name=name;//1.用"this.成员变量名称"和重名的局部变量区分开来	}	Person(String name,int age){		this(name);		this.age=age;	}	String getInfo(){//成员方法		return "姓名:" + name + "\n年龄:" + age;	}	void print(){		System.out.println(this.getInfo());//2.用"this.成员方法名"访问成员方法。		System.out.println(getInfo());//这种情况this关键字一般不写,让编译器自动添加。	}}public class Test0505{	public static void main(String[] args){		Person p=new Person("张三",33);		p.print();	}}
class Person{	private String name;	private int age;	Person(){}	Person(String name){//不含this()的构造方法		this.name=name;	}	Person(String name,int age){//在构造方法内调用另一个构造方法		this(name);//3."this();"访问构造方法必须放在构造方法的第一行		this.age=age;	}	String getInfo(){		return "姓名:" + name + "\n年龄:" + age;	}	void print(){		System.out.println(this.getInfo());	}}public class Test0505{	public static void main(String[] args){		Person p=new Person("张三",33);		p.print();	}}
class Leaf{	private int i=0;	Leaf increment(){		i++;		return this;//4.返回对当前对象的引用。	}	void print(){		System.out.println("i="+i);	}}public class Test0505{	public static void main(String[] args){		Leaf x=new Leaf();		x.increment().increment().increment().print();	}}
class Person{	void eat(Apple apple){		Apple peeled=apple.getPeeled();		System.out.println(peeled);	}}class Apple{	Apple getPeeled(){		System.out.println(this);//输出对当前对象的引用。		return Peeler.peel(this);//5.将对当前对象的引用作为参数传递给其他方法。	}}class Peeler{	static Apple peel(Apple apple){		return apple;	}}public class Test0505{	public static void main(String[] args){		Apple a=new Apple();		System.out.println(a);		new Person().eat(a);	}}

推荐教程:java快速入门

以上就是java中什么是this的详细内容,更多请关注搞代码gaodaima其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:java中什么是this

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址