this是指当前对象自己
来源:互联网 发布:mac如何连接远程服务 编辑:程序博客网 时间:2024/05/19 13:15
1. this是指当前对象自己。
当在一个类中要明确指出使用对象自己的的变量或函数时就应该加上this引用。如下面这个例子中:
public class A {
String s = "Hello";
public A(String s) {
System.out.println("s = " + s);
System.out.println("1 -> this.s = " + this.s);
this.s = s;
System.out.println("2 -> this.s = " + this.s);
}
public static void main(String[] args) {
new A("HelloWorld!");
}
}
运行结果:
s = HelloWorld!
1 -> this.s = Hello
2 -> this.s = HelloWorld!
在这个例子中,构造函数A中,参数s与类A的变量s同名,这时如果直接对s进行操作则是对参数s进行操作。若要对类A的变量s进行操作就应该用this进行引用。运行结果的第一行就是直接对参数s进行打印结果;后面两行分别是对对象A的变量s进行操作前后的打印结果。
2. 把this作为参数传递
当你要把自己作为参数传递给别的对象时,也可以用this。如:
public class A {
public A() {
new B(this).print();
}
public void print() {
System.out.println("Hello from A!");
}
}
public class B {
A a;
public B(A a) {
this.a = a;
}
public void print() {
a.print();
System.out.println("Hello from B!");
}
}
运行结果:
Hello from A!
Hello from B!
在这个例子中,对象A的构造函数中,用new B(this)把对象A自己作为参数传递给了对象B的构造函数。
3. 注意匿名类和内部类中的中的this。
- this是指当前对象自己
- js函数中this是全局变量还是当前对象
- this表示当前对象
- JAVA this 当前对象
- $this关键字是用来访问当前对象中的对象属性和对象方法的系统变量
- 2.2.6对象锁synchronized(this)锁定的是当前对象
- Java this 返回当前对象
- 仔细确认当前this对象是否是你所想指定的元素
- 指向当前对象的this指针
- html获取当前对象this的标签
- 多线程之synchronized(this)锁定当前对象
- JQuery获取this当前对象子元素对象
- JQuery获取this当前对象子元素对象
- JQuery获取this当前对象子元素对象
- JQuery获取this当前对象子元素对象
- jQuery获取this当前对象子元素对象
- this关键字的作用 使用this调用其他构造方法 使用this表示当前对象
- js判断是否是当前点击对象
- 学习php的一些感悟!
- opencv cmake教程以及环境变量配置(转载)
- 第5周项目1(1)三角形类雏形
- 关于大非负整数乘法
- 始终伴随着一种信念
- this是指当前对象自己
- android学习之旅--BaseAdapter细节
- ssh免密码登陆简单原理
- codeforces--652B z-sort(sorting)
- 关闭sublime更新提醒
- Java中的多态性
- ZOJ 1203 Swordfish
- ubuntu12.04设置屏幕开机亮度
- 流量劫持与防范