java中什么时刻用this?
his只存在于要领内部,用来代表挪用改要领的对象。能够理解为每个要领内部都有一个局部变量叫this,每当初始化一个对象时,就把该对象的地点传递给了该对象每个要领中的this变量,从而能够在要领内部运用这个的对象。

java中什么时刻用this?
1、当局部变量和成员变量重名的时刻,在要领中运用this示意成员变量以示辨别
实例:
class Demo{
String str = "这是成员变量";
void fun(String str){
(str);
();
= str;
();
}
}
public class This{
public static void main(String args[]){
Demo demo = new Demo();
("这是局部变量");
}
}
2、this关键字把当前对象传递给其他要领
实例:
class Person{
public void eat(Apple apple){
Apple peeled = ();
("Yummy");
}
}
class Peeler{
static Apple peel(Apple apple){
//....remove peel
return apple;
}
}
class Apple{
Apple getPeeled(){
return Peeler.peel(this);
}
}
public class This{
public static void main(String args[]){
new Person().eat(new Apple());
}
}
3、当须要返回当前对象的引用时,就常常在要领写return this
这类做法的优点是:当你运用一个对象挪用该要领,该要领返回的是经由修改后的对象,且又能运用该对象做其他的操纵。因而很轻易对一个对象举行屡次操纵。
public class This{
int i = 0;
This increment(){
i += 2;
return this;
}
void print(){
("i = " + i);
}
public static void main(String args[]){
This x = new This();
().increment().print();
}
}
效果为:4
4、在组织器中挪用组织器须要运用this
一个类有很多组织函数,有时刻想在一个组织函数中挪用其他组织函数,以防止代码反复,能够运用this关键字。

THE END






