其他分享
首页 > 其他分享> > This的用法

This的用法

作者:互联网

This 的用法

  1. this(); 用于调用重载的构造方法,只能在构造器方法中使用,且必须在第一行;
  2. this 不能再 static 方法中使用,因为staic在方法区中,找不到this,普通方法会默认传入this作为隐式参数;
  3. 普通方法中 this 指向调用该方法的对象,构造方法中,this 指向准备初始化的对象。
public class TestThis {

    int a,b,c;

    public TestThis() {
        this(2); // 调用有参构造器
        System.out.println("空参构造方法初始化对象:" + this);

    }

    public TestThis(int a){
        //this();  //调用无参构造器
        System.out.println("有参构造方法初始化对象:" + this);
        this.a = a;
    }
    public void Test(){
        System.out.println("普通方法对象:" + this);
    }

    public static void main(String[] args) {
        TestThis testThis = new TestThis();
        testThis.Test();
    }
}

标签:构造方法,TestThis,System,用法,println,public,out
来源: https://blog.csdn.net/qq_43279230/article/details/123141069