【JAVA基础】this关键字的使用

来源:互联网 发布:淘宝大学商学院哪个好 编辑:程序博客网 时间:2024/05/29 15:30

this

this这个关键字,在刷左程云的书的时候总是有很多题目的解法都是this.贯穿整个类的始末。很好奇把它们全部去掉会怎样?是会在所有情况下都错,还是在部分情况下会错,还是所有情况下都没任何问题? 还是以上三种情况在不同类上会有不同的解答

以上 是在我还不了解this.的作用的时候产生的疑问


用类名定义一个变量的时候,定义的只是一个引用,外面可以通过这个引用来访问这个类里面的属性和方法。

类里面也应该有一个引用来访问自己的属性和方法

JAVA提供了一个很好的东西,就是 this 对象,它可以在类里面来引用这个类的属性和方法。先来个简单的例子:

public class ThisDemo {      String name="Core";    public void print(String name){        System.out.println("类中的属性 name="+this.name);        System.out.println("局部传参的属性="+name);    }       public static void main(String[] args) {        ThisDemo tt=new ThisDemo();        tt.print("外部入侵");    }}

类中的属性 name= Core
局部传参的属性=外部入侵


关于返回类自身的引用,《Thinking in Java》有个很经典的例子。

public class ThisDemo {      int number;    ThisDemo increment(){         number++;         return this;    }    private void print(){         System.out.println("number="+number);    }    public static void main(String[] args) {        ThisDemo tt=new ThisDemo();         tt.increment().increment().increment().print();    }}

一个类中定义两个构造函数,在一个构造函数中通过 this 这个引用来调用另一个构造函数。

public class ThisDemo {      String name;    int age;    public ThisDemo (){         this.age=25;   }         public ThisDemo(String name,int age){        this();        this.name="vermouth";    }       private void print(){         System.out.println("最终名字="+this.name);         System.out.println("最终的年龄="+this.age);    }    public static void main(String[] args) {       ThisDemo tt=new ThisDemo("",0); //随便传进去的参数       tt.print();    }}

输出结果

最终名字=vermouth
最终的年龄=25

0 0