Java this关键字
来源:互联网 发布:本周10月重要经济数据 编辑:程序博客网 时间:2024/09/21 11:16
Java class中定义的method(方法)字节码存在方法区中(什么是方法区?请自行搜索Java内存结构),不论有多少基于这个class的对象,这些对象的method都只有一份,就是方法区中的class method字节码,所有这个class的对象调用的method都来自同一片内存。
Class ThisClass {
void f(int i) { ... }
public static void main(String args) {
ThisClass a = new ThisClass();
ThisClass b = new ThisClass();
a.f(2);
b.f(2);
}
}
上例中a,b所指向的对象调用的f方法实际上是同一片method字节码,那么f method怎么知道是哪个对象调用的自己呢?其实后台调用的时候并非像代码里一样,编译器帮我们完成了一些工作,后台实际调用的时候会把这个对象本身当成f 的第一个参数传进去,像下面这样:
ThisClass.f(a, 2);
ThisClass.f(b, 2);
上面的例子看不出专递对象句柄到method里有什么用,但是如果在f method中需要用到当前调用对象的句柄(比如需要返回当前对象),我们就需要this关键字。this关键字就指向调用这个method的对象。下例来自Thinking in Java 4th Edition
//: Leaf.java // Simple use of the "this" keyword 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(); } } ///:~
this关键字常用于class构造方法中:
class ThisClass {int num = 0;ThisClass(int i) {num = i;}ThisClass() {this(10);}}
对于static方法,编译器并没有在后台‘秘密’转入调用它的对象,因为调用static方法不需要对象,所以static method是没有this变量的。
0 0
- Java this关键字,static关键字
- java 关键字this
- java中的this关键字
- java this 关键字
- Java基础: 关键字 this
- java 中的this关键字
- java中的this关键字
- java this关键字
- java中的this关键字
- Java--this关键字
- JAVA this 关键字
- JAVA关键字this
- java中的关键字this
- java 中的关键字 this
- java中this关键字
- Java中this关键字
- java中this关键字
- java之this关键字
- OpenCV基础篇之绘图及RNG随机数对象
- java小结_021_交通灯
- OpenCV基础篇之像素访问
- 使用Pspice进行电路仿真
- OpenCV基础篇之图片叠加
- Java this关键字
- 循环的角度求均值
- OpenCV基础篇之使用CMake管理工程
- OpenCV基础篇之查找表
- CentOS上编译安装OpenCV-2.3.1与ffmpeg-2.1.2
- OpenCV基础篇之读取显示图片
- OpenCV基础篇之像素操作对比度调节
- DSP/BIOS使用之初窥门径——滴答时钟及烧写Flash
- PCB设计资料:看到最后才知道是福利