java关键字——this
来源:互联网 发布:网络雨晴引导员 编辑:程序博客网 时间:2024/05/22 12:18
this表示对“调用方法的那个对象”的引用。它只能在方法内部使用。this的用法和其他对象引用并无不同。
一.主要用法:
1)表示对当前对象的引用!
2)表示用类的成员变量,而非函数参数。
3)在构造器中调用构造器。
1)对当前对象的引用
在java编程思想(Thinking in Jaba)中有这么一个例子:
public class Leaf{ 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关键字返回了对当前对象的引用,所以很容易在一条语句里对同一个对象执行多次操作。
this关键字对于将当前对象传递给其他方法也很有用。
class person{ public void eat(Apple apple){ Apple peeled =apple.getPeeled(); System.out.println("Yummy"); }}class Peeler{ static Apple peel(Apple apple){ //。。。。 return apple; }}class Apple{ Apple getPeeled(){ return Peeler.peel(this); }}public class PassingThis{ public static void main(String[] args){ new Person.eat(new Apple()); }}输出:YummyApple需要调用Peeler.peel()方法,它是一个外部的工具方法,为零将其自身传递给外部方法,Apple必须使用this关键字。
2)调用类的成员变量。
public class Flower{int petalCount =0;String s="initial value";Flower(){this("hi",47);System.out.println("default constructor(no args)");}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);}Flower(String s,int petals){this(petals);//调用构造方法必须放在最起始处。//this(s); 不能调用构造方法两次。this.s=s; System.out.println("String &int args");}void printPetalCount(){//this.s(11);System.out.println("petalCount="+ PetalCount +" s= "+s);}public static void main(String[] args){Flower x=new Flower();x.printPetalCount();}}在方法Flower(String s,int petals)中,形式参数和成员变量s会有冲突,所以我们可以使用this.s表示类的成员变量,而“=”后面的s则是方法中的参数,这样就可以将参数赋值给成员变量了。在java代码中经常出现这种写法。
3)构造器中调用构造器
构造器不会的可以看这里(点击打开链接),在方法Flower(String s,int petals)中this(petals)调用构造方法,它必须放在最起始处。并且在一个构造方法中最多只能调用其他的构造方法一次,如果写两个的话,编译就会出错。
0 0
- java关键字——this
- Java——this关键字
- this关键字——java
- Java——This关键字
- java关键字之—this
- java学习笔记——this关键字
- Java关键字——super、this
- java学习日记——this关键字
- Java复习——this关键字
- Java——this关键字总结
- Java基础—super和this关键字
- JAVA—Super和this关键字
- java笔记——传递与this关键字
- Java基础知识——引用传递、this关键字
- 【小白的java成长系列】——this关键字
- 黑马程序员——Java(this关键字用法)
- 黑马程序员——Java基础---this和super关键字
- 黑马程序员——Java基础:面向对象、this关键字
- Could not initialize class com.android.xml.AndroidXPathFactory解决办法
- 两个排序数组第k大的数
- 图像处理与计算机视觉:基础,经典以及最近发展
- 15北京网络赛 E题
- C++派生类构造函数调用顺序
- java关键字——this
- JAVA取整以及四舍五入
- android开发游记:CROP 大图片裁剪原理分析
- Swift一句话总结-将变量和常量加入字符串中
- Java内存溢出的详细解决方案
- 100%成功 mysql高版本导入低版本数据库
- Android中选取并绑定AppWidget
- iOS 开发 证书申请 和打包
- CentOS7安装Hadoop2.7完整流程