this关键字是面向对象编程里面的一个比较重要的概念。学好this关键字可以更深入地理解面向对象传递引用的运用。我们先给大家说一下this关键字的几个特点 (1)this,代表一个类的对象,或者说就是本类的对象 (2)this不能用在static静态方法中 (3)this不能单独出现,要出现都在方法中使用
我们来看几个示例:
- class TestThis {
- public int a;
- public TestThis(int a) {
- this.a = a;
- System.out.println(this.a);
- System.out.println(a);
- }
- public static void main(String[] args) {
- new TestThis(100);
- }
- }
上面的代码用到this关键字,其中需要给大家解释一下“this.a”这个用法 (1)它相当于对象打点调用变量的应用 (2)一般在一个方法中,局部变量和全局变量同名时,局部变量在方法的使用会将全局的变量隐藏掉。如果你想在一个方法中使用全局变量,就可以this.全局变量名
示例二:
- class TestThis {
- public void dis() {
- System.out.println("===dis方法===");
- }
- public void method() {
- this.dis(); //方法之间也可以利用this关键字打点调用其他方法
- }
- public static void main(String[] args) {
- new TestThis(100);
- }
- }
示例二代码:告诉我们“方法之间也可以利用this关键字打点调用其他方法”