java this的使用(翻译自Java Tutorials)
2012-11-28 19:39
405 查看
原文出自 http://www.cnblogs.com/ggjucheng/archive/2012/11/28/2793257.html
例如,Point类是这样写的:
但是它也可以这么写:
构造方法的每个参数都隐藏了对象的字段---在构造方法里,x是构造方法的第一个参数的局部副本,引用
这个类有一系列构造方法,每个构造方法初始化
如果存在,另一个构造函数的调用必须是构造函数中的第一行。
[b]前言[/b]
在一个实例方法或者是构造方法中,this引用指向当前的对象---方法调用或者是构造方法调用的对象。你可以在实例化方法或者构造方法中,使用this引用任何成员。[b]在字段中使用this[/b]
使用this关键字的最常见的原因,是字段被方法或构造函数的参数隐藏了。例如,Point类是这样写的:
public class Point { public int x = 0; public int y = 0; //constructor public Point(int a, int b) { x = a; y = b; } }
但是它也可以这么写:
public class Point { public int x = 0; public int y = 0; //constructor public Point(int x, int y) { this.x = x; this.y = y; } }
构造方法的每个参数都隐藏了对象的字段---在构造方法里,x是构造方法的第一个参数的局部副本,引用
Point字段x,构造方法必须使用this.x.
[b]在构造方法使用this[/b]
在构造方法里,你可以使用this关键字调用类的另一个构造方法。这种是显式构造方法调用。这里有一个Rectangle类:
public class Rectangle { private int x, y; private int width, height; public Rectangle() { this(0, 0, 0, 0); } public Rectangle(int width, int height) { this(0, 0, width, height); } public Rectangle(int x, int y, int width, int height) { this.x = x; this.y = y; this.width = width; this.height = height; } ... }
这个类有一系列构造方法,每个构造方法初始化
Rectangle的部门变量。如果没有为参数提供初始化值,构造方法为每个成员变量提供了默认值。例如,无参构造方法,传入四个值为0的参数,调用四个参数的构造方法,还有两个参数的构造方法,传入两个0的参数,调用四个参数的构造方法。之前说过,编译器是根据参数的个数和类型,决定调用哪个构造方法。
如果存在,另一个构造函数的调用必须是构造函数中的第一行。
相关文章推荐
- java使用接口(翻译自Java Tutorials)
- java super的使用(翻译自Java Tutorials)
- Encog3Java-User.pdf翻译:第十章 使用自组织映射
- java while和do-while语句(翻译自Java Tutorials)
- 使用jdbc连接mysql 出现 java.sql.Exception: this specifer does...(root@'%')..doesn't exist.
- 对Java方法内部使用this访问成员变量的深入理解
- java中this.的使用;什么是构造方法,及构造方法的作用
- Fragment中使用出现的java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
- JAVA程序中this的使用
- 【翻译】《Java™ I/O, 2nd Edition》-14.1 使用缓冲区复制文件
- Java/android 里ClassName.this和this的使用
- Java关键字this、super使用总结
- JavaEE Tutorials (7) - 在会话bean中使用异步方法调用
- JAVA:this的使用
- java中this的使用
- Java(方法重写与变量覆盖)(super,this的使用)
- Java关键字this、super使用总结
- 浅谈 Java 中 this 的使用
- Java (九) this与super关键字在继承中的使用