`

The this keyword(Java中this关键字)

 
阅读更多

The this keyword(this关键字)
If you have two objects of the same type called a and b, you might wonder how it is that you can call a method peel( ) for both those objects:

如果有同一个类型的两个对象a和b,你可能想知道如何a和b对象都能调用peel这个方法:
//: initialization/BananaPeel.java

class Banana { void peel(int i) { /* ... */ } }
public class BananaPeel {
public static void main(String[] args) {
Banana a = new Banana(),
b = new Banana();
a.peel(1);
b.peel(2);
}
}





If there’s only one method called peel( ), how can that method know whether it’s being called for the object a or b?

如果只有一个peel(),它如何知道是a还是b调用的呢?
To allow you to write the code in a convenient object-oriented syntax in which you “send a message to an object,” the compiler does some undercover work for you. There’s a secret first argument passed to the method peel( ), and that argument is the reference to the object that’s being manipulated. So the two method calls become something like:

为了能用简便、面向对象的语法编写代码,即使用"发送消息给对象",编译器在幕后做了一些工作。 它暗自把"所操作对象的引用"作为第一个参数传递给peel()。 所以上述的两个方法的调用变成这样:

Banana.peel(a, 1);
Banana.peel(b, 2);





This is internal and you can’t write these expressions and get the compiler to accept them, but it gives you an idea of what’s happening.

这是内部表示形式,并不能这样书写代码,并且试图编译通过,但这种写法的确帮助我们理解实际发生的事情。
Suppose you’re inside a method and you’d like to get the reference to the current object. Since that reference is passed secretly by the compiler, there’s no identifier for it. However, for this purpose there’s a keyword: this. The this keyword—which can be used
only inside a non-static method —produces the reference to the object that the method has been called for. You can treat the reference just like any other object reference. Keep in mind that if you’re calling a method of your class from within another method of your class, you don’t need to use this. You simply call the method. The current this reference is automatically used for the other method. Thus you can say:
//: initialization/Apricot.java

public class Apricot {
void pick() { /* ... */ }
void pit() { pick(); /* ... */ }
}






Inside pit( ), you could say this.pick( ) but there’s no need to. 1 The compiler does it for you automatically. The this keyword is used only for those special cases in which you need to explicitly use the reference to the current object. For example, it’s often used in return statements when you want to return the reference to the current object:
1 Some people will obsessively put this in front of every method call and field reference, arguing that it makes it “clearer and more explicit.” Don’t do it. There’s a reason that we use high-level languages: They do things for us. If you put this in when it’s not necessary, you will confuse and annoy everyone who reads your code, since all the rest of the code they’ve read won’t use this everywhere. People expect this to be used only when it is necessary. Following a consistent and straightforward coding style saves time and money.

//: initialization/Leaf.java
// Simple use of the "this" keyword.

public class Leaf {
int i = 0;
Leaf increment() {
i++;
return this;
}
void print() {
System.out.println("i = " + i);
}
public static void main(String[] args) {
Leaf x = new Leaf();
x.increment().increment().increment().print();
}
}





/* Output:
i = 3
*///:~
Because increment( ) returns the reference to the current object via the this keyword (通过this关键字返回当前对象的引用), multiple operations can easily be performed on the same object.
The this keyword is also useful for passing the current object to another method:

this关键字对于将当前对象传递给其他方法也很有用:
//: initialization/PassingThis.java

package com.test;
@SuppressWarnings("unused")
class Person1 {
	public void eat(Apple apple) {
		Apple peeled = apple.getPeeled();
		System.out.println("Yummy");
	}
}

class Peeler {
	static Apple peel(Apple apple) {
		// ... remove peel
		return apple; // Peeled
	}
}

class Apple {
	Apple getPeeled() {
		return Peeler.peel(this);
	}
}
/**
 * 程序传递当前对象
 * 调用顺序:首先调用Person1的eat方法,当前对象为Person1的对象。
 * 接着当前对象为apple,调用Apple的getPeeled方法,最终返回一个apple对象的引用。
 * @author 守望幸福
 *
 */
public class PassingThis {
	public static void main(String[] args) {
		new Person1().eat(new Apple());//调用eat方法
	}
}

/* Output:
Yummy
*///:~
Apple needs to call Peeler.peel( ), which is a foreign utility method that performs an operation that, for some reason, needs to be external to Apple (perhaps the external method can be applied across many different classes, and you don’t want to repeat the code). To pass itself to the foreign method, it must use this.

package com.test;
/**
 * first第二个调用second方法实际编写时不需要添加this,编译器会自动添加
 * @author 守望幸福
 *
 */
public class ThisExcise {
	void first(){
		second();
		this.second();
		System.out.println(this.getClass());//class com.test.ThisExcise
	}
	void second(){
		System.out.println("I had called!");
	}
	public static void main(String[] args) {
		new ThisExcise().first();
	}
}
 
//返回当前对象的引用
package com.test;
/**
 * this关键字只能在非static方法内使用,表示对"调用方法的那个对象"的引用。
 * increment方法的调用为tk,因此retrun this;表示返回tk对象的引用。
 * 调用之后的类型为ThisKeyword
 * @author 守望幸福
 *
 */
public class ThisKeyword {
	int i=0;
	ThisKeyword increment(){
		i++;
		return this;
	}
	void print(){
		System.out.println("i="+i);
	}
	public static void main(String[] args) {
		ThisKeyword tk=new ThisKeyword();
		System.out.println(tk.increment().getClass());//class com.test.ThisKeyword  i=1
		System.out.println(tk.increment().increment().getClass());//class com.test.ThisKeyword i=3
		tk.increment().increment().print();//i=5
	}
}
分享到:
评论

相关推荐

    高亮显示关键字

    高亮显示 关键字 function HeightLight(Keyword) { //文本选择器 var TextRange; //是否找到 var Found=false; //找到的次数 var Count = 0; TextRange = document.body.createTextRange(); Found = ...

    search_keyword12.rar_Java关键字

    java脚本搜索关键字,脚本说明.

    LS-DYNA关键字手册

    LS-DYNA关键字手册,详细讲述了LS-DYNA中的关键字作用

    java关键字总结

    全新编译汇总的 java关键字总结 简单明了 原始资料来源于网络,后经个人加工

    Java关键字详解

    详细解释了Java中的各个关键字,包括它们的中文名称、含义等等。

    keywordSQL:Java 中的所有 SQL 关键字

    关键字SQL 我列出了主要数据库供应商的所有关键字, 它们转换为类中的方法。 现在您可以调用这些方法,就像在 Stringbuilder 中编写一系列文本一样。 ##我能写多少复杂度SQL语句? 像你想要的那样复杂。 示例:列出...

    编程技能训练与等级考试辅导:this关键字.pptx

    9.14 this关键字学习目标理解this引用会正确使用this引用数据域会正确使用this引用构造方法9.14 this关键字(The this Keyword ) This是用来引用自身对象的引用名,其作用:在实例方法或构造方法内部引用自身对象的...

    eslint-plugin-arrow-require-this:已弃用:ESLint规则要求箭头功能引用“ this”关键字

    arrow-require-this ESLint Rule需要=>箭头函数来引用this关键字。 它还支持“从不”配置,这意味着=>箭头函数不应使用this 。 该规则的主要目的是防止将=>箭头函数用作函数的简写形式(即arr.map(x => x * 2) ),...

    高德定位与poi关键字搜索

    实现了高德地图定位,自定义定位图标,点击定位点,弹出小窗口(有定位点的详细信息),点击marker图标让窗口消失。实现了poi关键字搜索,除了官方api的功能外,加上了点击marker点之外的地方,窗口亦能消失。

    keyword-popularity:获取带有特定关键字的npm软件包数

    关键字受欢迎度 使用特定关键字获取npm软件包的数量。...-h --help Print a short synopsis (-h) or this help text (--help) 例子 $ keyword-popularity cli tool cli-tool KEYWORD POPULARITY cli

    关键字爬取百度图片

    最近在做毕设,需要自己制作数据集,通过关键字爬取省时省力

    python关键字.pdf

    python关键字(简) >>> import keyword >>> keyword.kwlist ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', '...

    ssd5 ex4 给需要帮助的人。这是ssd5 ex4

    This method a new instance of a Listing object that contains only those advertisements whose name or description contains the string given by the parameter keyword. If the parameter keyword equals ...

    词法分析器java

    编译词法分析器,用java编写的 public class analyetest { public ArrayList bracket; public ArrayList keyword; public ArrayList symbol; public ArrayList semicolon; public ArrayList operator; ...

    robotframework-java-keyword:java中创建robotframework关键字库的示例代码,使用maven插件

    robotsframework-java-keyword java中创建robotframework关键字库的示例代码,使用maven插件要运行测试,请键入以下命令: mvn机器人框架:运行mvn 整数测试

    Hypermesh菜单上的关键字释意(按字母排序)[文].pdf

    Hypermesh菜单上的关键字释意(按字母排序)[文].pdf

    关键字修饰符「Keyword Modifier」-crx插件

    在使用Adwords或Bing Ads时,只需打开应用程序,然后将关键字粘贴到文本框中,然后选择关键字类型即可。 V2.1更新:-在获得社区输入后,从Modified Broad Match关键字中排除了常见介词/文章(通过电子邮件将您对此...

    Java 7 Concurrency Cookbook

    Locks and the synchronized keyword are explained in detail. Chapter 3, Thread Synchronization Utilities will teach the readers to use the high-level utilities of Java to manage the synchronization ...

    Interactive.Object.Oriented.Programming.in.Java

    Discover object oriented programming with Java in this unique tutorial. This book uses Java and Eclipse to write and generate output for examples in topics such as classes, interfaces, overloading, ...

Global site tag (gtag.js) - Google Analytics