关于this的使用

this作为对象的默认引用有两种:

  1.构造器中引用该构造器执行初始化对象

  2.在方法中引用调用该方法的对象

最大的作用是让类中的方法访问该类中的另一个方法或属性!(static 修饰的方法中不能使用this引用)

当局部变量与属性同名时,使用this关键字!

  举个例子:

public class TestThis {
    String name="小黑";
    public void PlayBall(String name){
        System.out.println(name);
        System.out.println(this.name);
        System.out.println(this.name+",一起去打球吧!");
        this.name = name;
        System.out.println(name+",一起去打球吧!");
    }

    public static void main(String[] args) {
        //这里的PlayBall方法是非静态的,需要通过new一个对象来调用
        String name = "小白";
        TestThis testThis = new TestThis();
        testThis.PlayBall(name);
    }

}
//输出结果
小白
小黑
小黑,一起去打球吧!
小白,一起去打球吧!  

猜你喜欢

转载自www.cnblogs.com/qingfengdream/p/11785873.html