`

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
	}
}
分享到:
评论

相关推荐

    search_keyword12.rar_Java关键字

    本文将深入探讨Java中的关键字,并结合"search_keyword12.doc"和"www.pudn.com.txt"这两个文件中的内容,提供更全面的理解。 1. Java关键字分类: - 访问修饰符:如public、private、protected,用于控制类、方法...

    JAVA中的保留关键字

    ### JAVA中的保留关键字 在Java编程语言中,关键字与保留关键字是极其重要的组成部分,它们定义了语言的基本结构和语法规则。对于初学者来说,熟悉这些关键字对于理解和编写正确的Java程序至关重要。 #### 关键字...

    源码关键字统计.rar

    在Java编程语言中,关键字是预定义的、具有特殊含义的词汇,它们是构成程序语法结构的基础元素。这篇关于“源码关键字统计”的主题旨在分析Java源代码文件,并计算其中出现的关键字数量。这个任务涉及到文件读取、...

    JAVA标识符关键字和数据类型.ppt

    Java中一些赋以特定的含义,用做专门用途的字符串称为关键字(keyword)。所有Java关键字都是小写英文字符串。goto和const虽然从未使用,但也作被为Java关键字保留。Java关键字包括: * 原始数据类型:byte、short...

    002-标识符和关键字_java_标识符和关键字_

    在Java编程语言中,标识符(Identifier)与关键字(Keyword)是两个至关重要的概念,它们构成了程序的基础结构。本文将详细解析这两个概念及其在Java中的使用规则。 首先,标识符是用来给变量、类、方法、接口等...

    Java中的保留字和关键字.doc

    在编程语言中,关键字(Keyword)和保留字(Reserved Word)是具有特殊含义的重要组成部分。对于Java这门广泛使用的面向对象编程语言而言,理解其关键字与保留字的含义及用途至关重要。本文将详细介绍Java中的关键字...

    Java关键字详解

    在Java编程语言中,关键字是具有特殊含义的保留词汇,它们不能作为变量名、类名或方法名。这些关键字对于理解和编写有效的Java代码至关重要。下面将详细解释Java中的各个关键字。 一、关键字总览: Java的关键字...

    Android ArrayList关键字查询.rar

    在Android开发中,ArrayList是一个非常重要的数据结构,它属于Java集合框架的一部分,但在Android环境中被广泛使用。ArrayList关键字查询是Android应用中常见的功能,尤其在显示大量数据的ListView中,用户通常需要...

    高德地图集成:定位功能 关键字检索POI 获取附近位置列表

    本文将详细讲解如何在您的项目中集成高德地图,利用其API实现定位功能、关键字检索POI(Point of Interest)以及获取附近位置列表。 **一、集成高德地图** 1. **注册开发者账号** 在使用高德地图API之前,首先...

    Android开发 高德地图SDK检索关键字demo

    在这个示例中,我们使用了SearchView组件进行关键字输入,当用户提交查询时调用`search关键词`方法。这个方法创建了一个`SearchManager`对象,并设置了搜索回调。在回调中,我们处理搜索结果,对每个搜索到的POI...

    ListView搜索关键字高亮显示

    this.highlightKeyword = keyword; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = super.getView(position, convertView, parent); TextView textView ...

    ListView实现简单的关键字高亮显示

    本教程将详细讲解如何在ListView中实现简单的关键字高亮显示。 首先,我们需要一个ListView来展示数据。在布局文件(如activity_main.xml)中添加ListView,并设置其ID: ```xml android:id="@+id/list_view" ...

    no-octal-constants-above-256.rar_The Test

    【描述】"This test verifies that the keyword cannot be used as an identifier for Java." 指出,此测试的核心在于验证Java中关键字不能被用作标识符。在Java中,标识符是用来命名变量、类、方法等的符号,它们...

    java考试题及答案借鉴.pdf

    在给定的选项中,A) `$persons`,B) `TwoUsers`,E) `_endline`是合法的标识符,而C) `*point`和D) `this`不符合规则,`this`是Java中的一个关键字。 6. **运算符优先级**:表达式`y += z-- / ++x`的计算中,先进行...

    词法分析器java

    - **initKeyword()**: 添加了一系列Java关键字到 `KEYWORD` 映射表中。这些关键字包括但不限于 `class`, `package`, `this`, `abstract`, `boolean`, `break`, `byte`, `case`, `cast`, `catch`, `char`, `continue`...

    Android 关键字动画飞入效果

    本教程将深入探讨如何在Android中实现关键字飞入效果。 首先,Android中的动画分为两种主要类型:属性动画(Property Animation)和视图动画(View Animation)。视图动画主要应用于API 11及以下版本,而属性动画是...

    Javascript实现一个简单的输入关键字添加标签效果实例

    在JavaScript编程中,实现一个简单的输入关键字添加标签的效果可以为用户界面增添互动性和实用性。这个功能常见于社交媒体、博客系统以及各种需要用户自定义标签的场合。以下将详细讲解如何利用JavaScript来完成这一...

    六个有用的java过滤器

    在Java Web开发中,过滤器(Filter)是一种非常重要的技术,它能够对用户的请求和响应进行预处理或后处理,从而实现各种功能需求,例如设置缓存策略、登录验证、字符编码转换等。下面我们将详细探讨标题和描述中提到...

Global site tag (gtag.js) - Google Analytics