Java中“this”的理解

来源:互联网 发布:mysql读写分离实现 编辑:程序博客网 时间:2024/06/16 04:16

1.  this是指当前对象自己。 

    当在一个类中要明确指出使用对象自己的的变量或函数时就应该加上this引用。如下面这个例子中: 
  1. public class A {   
  2.   
  3.   String s = "Hello";   
  4.      
  5.   public A(String s) {   
  6.     System.out.println("s = " + s);   
  7.     System.out.println("1 -> this.s = " + this.s);   
  8.     this.s = s;   
  9.     System.out.println("2 -> this.s = " + this.s);   
  10.   }   
  11.      
  12.   public static void main(String[] args) {   
  13.     new A("HelloWorld!");   
  14.   }   
  15. }   
运行结果: 
s = HelloWorld! 
1 -> this.s = Hello 
2 -> this.s = HelloWorld! 

在这个例子中,构造函数A中,参数s与类A的变量s同名,这时如果直接对s进行操作则是对参数s进行操作。若要对类A的变量s进行操作就应该用this进行引用。运行结果的第一行就是直接对参数s进行打印结果;后面两行分别是对对象A的变量s进行操作前后的打印结果。


















0 0
原创粉丝点击