《Java编程思想》学习笔记(四)——this总结
2011-06-26 10:15
281 查看
用法一:引用当前对象的成员变量:如果在类的方法中定义了与类的成员变量同名的局部变量, 则在该方法中,类的成员变量会被覆盖,为了在该方法中引用类的成员变量,则用到了this,例如:
用法二:将当前对象作为参数传递:有时候,在类的某一个方法中需要调用一个外部方法,该方法的参数是该类的对象,这种情况下,调用时便可将this传递进去。例如:
用法三:在类的重载构造函数中调用其他构造函数:当一个类有多个构造函数时,为了增加代码的复用,可以在一个构造函数中调用其他构造函数,但,只允许在当前构造函数中的第一句调用一次其他构造函数,否则将无法编译通过,如下面代码所示:
用法四:在内部类或匿名类中的用法,还未接触,待补充
注意:1、this不能用在static方法里 2、在构造函数中通过this调用其他构造函数的时候只能放在第一句
package com.exercise; public class Test { /** * @param args */ int i = 0; public void print() { int i = 1; System.out.println(i); System.out.println(this.i); } public static void main(String[] args) { // TODO Auto-generated method stub Test test = new Test(); test.print(); } }
用法二:将当前对象作为参数传递:有时候,在类的某一个方法中需要调用一个外部方法,该方法的参数是该类的对象,这种情况下,调用时便可将this传递进去。例如:
class Person { 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); } } public class PassingThis { public static void main(String[] args) { new Person().eat(new Apple()); } }
用法三:在类的重载构造函数中调用其他构造函数:当一个类有多个构造函数时,为了增加代码的复用,可以在一个构造函数中调用其他构造函数,但,只允许在当前构造函数中的第一句调用一次其他构造函数,否则将无法编译通过,如下面代码所示:
package com.exercise; public class Test { public int i; Test(int i) { this.i = i; } Test(String s) { System.out.println(s); } Test(int i, String s) { this(s); //this(i); 编译无法通过 this.i = i; } public static void main(String[] args) { Test test = new Test(6, "Hello"); System.out.println(test.i); } }
用法四:在内部类或匿名类中的用法,还未接触,待补充
注意:1、this不能用在static方法里 2、在构造函数中通过this调用其他构造函数的时候只能放在第一句
相关文章推荐
- 《Java编程思想》学习笔记1——面向对象和JVM基础
- this关键字和实体类的总结
- 《java编程思想》学习笔记(二)
- 总结函数声明提升,闭包,作用域,this
- synchronized(this)总结
- java--关键字this、super使用总结
- java中this的总结
- JavaScript学习总结(三)——this、原型、javascript面向对象
- 一切都是对象(《Java编程思想》第二章总结)
- 《Java编程思想》学习笔记12——Java new I/O(一)
- java知识总结(四)this与static详解
- this的用法总结(java/js/flex)
- Java中this和super的用法总结
- Java关键字this的用法总结
- 黑马程序员--this与base总结
- Java关键字this、super使用总结
- java面试题总结之super()与this()的区别
- THIS的指代总结
- Javascript中函数调用与this所指对象关系进行了一下总结
- Java中this和super的用法总结