Java中 “this” 关键字的使用

来源:互联网 发布:世界销售网络分布图 编辑:程序博客网 时间:2024/05/16 14:32

1、"this" 关键字的简单使用

public class Leaf {private 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();}}
运行结果:

i = 3

由于increment()通过this 关键字返回当前对象的句柄,所以可以方便地对同一个对象执行多项操作。

2、通过 “this” 关键字在构造函数里调用其他的构造函数

若为一个类写了多个构建器,那么经常都需要在一个构建器里调用另一个构建器,以避免写重复的代码。可
用this 关键字做到这一点。
通常,当我们说this 的时候,都是指“这个对象”或者“当前对象”。而且它本身会产生当前对象的一个句
柄。在一个构建器中,若为其赋予一个自变量列表,那么this 关键字会具有不同的含义:它会对与那个自变
量列表相符的构建器进行明确的调用。这样一来,我们就可通过一条直接的途径来调用其他构建器。如下所
示:
public class Flower {private int petalCount = 0;private String s = new String("null");Flower(int petals) {petalCount = petals;System.out.println("Constructor int arg only,"+ " petalCount = " + petalCount);}Flower(String ss) {System.out.println("Constructor String arg only,"+ " s = " + ss);s = ss;}Flower(String s, int petals) {this(petals); //构建器调用必须是我们做的第一件事情,否则会收到编译程序的报错信息。//! this(s); // Can't call two!this.s = s; // Another user of "this"System.out.println("String & int args");}Flower() {this("hi", 47);System.out.println("default constructor (no args)");}private void print() {System.out.println("petalCount = " + petalCount + " s = " + s);}public static void main(String[] args) {Flower x = new Flower();x.print();}}

运行结果:

其中,构建器Flower(String s,int petals)向我们揭示出这样一个问题:尽管可用this 调用一个构建器,
但不可调用两个。除此以外,构建器调用必须是我们做的第一件事情,否则会收到编译程序的报错信息。
这个例子也向大家展示了this 的另一项用途。由于自变量s 的名字以及成员数据s 的名字是相同的,所以会
出现混淆。为解决这个问题,可用this.s 来引用成员数据。

0 0
原创粉丝点击