源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

java中this的用法示例(关键字this)

  • 时间:2022-11-14 18:54 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:java中this的用法示例(关键字this)
this是指向本身的隐含的指针,简单的说,哪个对象调用this所在的方法,那么this就是哪个对象。 示例代码: TestThis_1.java
[u]复制代码[/u] 代码如下:
/* 问题:什么是this  * 输出结果:  * A@4e44ac6a  */ public class TestThis_1 {     public static void main(String[] args) {         A aa = new A();         System.out.println(aa.f()); //aa.f(), 返回aa这个对象的引用(指针)     }   } class A {     public A f() {         return this;  //返回调用f()方法的对象的A类对象的引用     }   }
this的常见用法 1. 区分同名变量 示例代码: TestThis_2.java
[u]复制代码[/u] 代码如下:
/* this的常见用法1:区分同名变量  * 输出结果:  * this. i = 1  * i = 33  */ public class TestThis_2 {     public static void main(String[] args) {         A aa = new A(33);     }   } class A {     public int i = 1;                                           //这个i是成员变量     /*注意:一般不这么写,构造函数主要是为了初始化,这么写主要是为了便于理解*/     public A(int i) {                                           //这个i是局部变量         System.out.printf("this. i = %dn", this.i);            //this.i指的是对象本身的成员变量i         System.out.printf("i = %dn", i);                       //这里的i是局部变量i     }   }
2. 构造方法间的相互调用 示例代码: TestThis_3.java
[u]复制代码[/u] 代码如下:
/* this的常见用法2: 构造方法中互相调用*/ public class TestThis_3 {     public static void main(String[] args) {     }   } class A {     int i, j, k;     public A(int i) {         this.i = i;     }       public A(int i, int j) {         /* i = 3;  error   如果不注释掉就会报错:用this(...)调用构造方法的时候,只能把它放在第一句          * TestThis_3.java:20: error: call to this must be first statement in constructor          *      this(i);          *                  ^          *                  1 error          */         this(i);            this.j = j;     }       public A(int i, int j, int k) {         this(i, j);         this.k = k;     }   }
注意事项 被static修饰的方法没有this指针。因为被static修饰的方法是公共的,不能说属于哪个具体的对象的。 示例代码: TestThis_4.java
[u]复制代码[/u] 代码如下:
/*static方法内部没有this指针*/ public class TestThis_4 {     public static void main(String[] args) {     }   } class A {     static A f() {         return this;         /* 出错信息:TestThis_4.java:10: error: non-static variable this cannot be referenced from a static context          *          return this;          *                     ^          *                     1 error          */     }   }
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部