>  기사  >  Java  >  Java에서 this 키워드는 무엇을 의미합니까?

Java에서 this 키워드는 무엇을 의미합니까?

王林
王林원래의
2019-11-18 15:03:4010116검색

Java에서 this 키워드는 무엇을 의미합니까?

이것은 무엇입니까?

이것은 객체 자체를 나타내는 객체이며 다음과 같이 이해될 수 있습니다. 포인터의 객체 자체를 가리키는 것입니다.

사용법은 다음과 같습니다.

"this.member 변수 이름"을 사용하여 동일한 이름을 가진 지역 변수와 구별합니다. 🎜🎜## 🎜🎜#

"this.member method name"을 사용하여 멤버 메소드에 액세스합니다.

class Person{
	private String name;//成员变量
	private int age;
	Person(){}
	Person(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();
	}
}

this() 액세스 생성자는 생성자의 첫 번째 줄에 배치되어야 합니다.

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);
	}
}
추천 튜토리얼: JavaTutorial

위 내용은 Java에서 this 키워드는 무엇을 의미합니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.