java语言 百分网手机站

java之this关键字用法事例解析

时间:2020-12-01 11:58:36 java语言 我要投稿

java之this关键字用法事例解析

  java之this关键字用法事例解析

  一、this使用范围

  1、在类的方法定义中使用的this关键字代表调用该方法对象的引用。

  2、当必须指出当前使用方法的对象是谁时,要使用关键字this。

  3、有时使用this可以处理方法中成员变量和参数重名的情况。

  4、this可以看做是一个变量,它的值是当前对象的'引用。

  注:this一般出现在方法中,当方法没有被调用时。并不知道this指向那个具体的对象。

  当某个对象调用有this的方法时,this就指向调用这个方法的对象。

  二、程序代码如下:

  public class TestThis{ private int i; public TestThis(int i){ this.i = i; } private TestThis increment(){ i += 1; return this; } public static void main (String[] args){ TestThis mTestThis = new TestThis(100); System.out.println(mTestThis.increment().increment().i); }}

  输出结果如下图所示:


【java之this关键字用法事例解析】相关文章:

1.Java中synchronized关键字的用法

2.解析Java中volatile关键字

3.Java中final关键字用法的讲解

4.Java关键字及注释

5.Java中Finally关键字

6.深入Java关键字null

7.理解java中的关键字

8.java的import关键字的使用