首页 > 其他 > 详细

This关键字的使用

时间:2019-12-30 12:51:05      阅读:66      评论:0      收藏:0      [点我收藏+]

* @author fengzhi-neusoft

 *

 * 本示例为了说明this的三种用法!

 */

package test;

public class ThisTest {

    private int i=0;

    //第一个构造器:有一个int型形参

    ThisTest(int i){

       this.i=i+1;//此时this表示引用成员变量i,而非函数参数i

       System.out.println("Int constructor i——this.i:  "+i+"——"+this.i);

       System.out.println("i-1:"+(i-1)+"this.i+1:"+(this.i+1));

       //从两个输出结果充分证明了i和this.i是不一样的!

    }

    //  第二个构造器:有一个String型形参

    ThisTest(String s){

       System.out.println("String constructor:  "+s);

    }

    //  第三个构造器:有一个int型形参和一个String型形参

    ThisTest(int i,String s){

       this(s);//this调用第二个构造器

       //this(i);

       /*此处不能用,因为其他任何方法都不能调用构造器,只有构造方法能调用他。

       但是必须注意:就算是构造方法调用构造器,也必须为于其第一行,构造方法也只能调

       用一个且仅一次构造器!*/

       this.i=i++;//this以引用该类的成员变量

       System.out.println("Int constructor:  "+i+"/n"+"String constructor:  "+s);

    }

    public ThisTest increment(){

       this.i++;

       return this;//返回的是当前的对象,该对象属于(ThisTest)

    }

    public static void main(String[] args){

       ThisTest tt0=new ThisTest(10);

       ThisTest tt1=new ThisTest("ok");

       ThisTest tt2=new ThisTest(20,"ok again!");

      

       System.out.println(tt0.increment().increment().increment().i);

       //tt0.increment()返回一个在tt0基础上i++的ThisTest对象,

       //接着又返回在上面返回的对象基础上i++的ThisTest对象!

    }

}


 

运行结果:


 

Int constructor i——this.i:  10——11

String constructor:  ok

String constructor:  ok again!

Int constructor:  21

String constructor:  ok again!

14


细节问题注释已经写的比较清楚了,这里不在赘述,只是总结一下,其实this主要要三种用法:

1、表示对当前对象的引用!

2、表示用类的成员变量,而非函数参数,注意在函数参数和成员变量同名是进行区分!其实这是第一种用法的特例,比较常用,所以那出来强调一下。

3、用于在构造方法中引用满足指定参数类型的构造器(其实也就是构造方法)。但是这里必须非常注意:只能引用一个构造方法且必须位于开始!

还有就是注意:this不能用在static方法中!所以甚至有人给static方法的定义就是:没有this的方法!虽然夸张,但是却充分说明this不能在static方法中使用!


 
————————————————
版权声明:本文为CSDN博主「fzfengzhi」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/fzfengzhi/article/details/2174406

This关键字的使用

原文:https://www.cnblogs.com/-answer/p/12119049.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!