JAVA中This的本质

this关键字

image-20220210164223611


this的本质:就是系统自动生成的隐藏的参数用来存放当前对象的地址
在每一个普通方法中都存在隐式参数this

this的其他要点:

  • this()调用重载的构造方法,避免相同的初始化代码。但只能在构造方法中用,并且必须位于构造方法的第一句。
  • this不能用于static方法中。
  • this是作为普通方法的“隐式参数”,由系统传入到方法中。
this的用法:

普通方法中,this总是指向调用该方法的对象。

示例:
public class TestThis {
    int a,b,c;
    void a(){
        System.out.println("指向调用该方法的对象1"+this);
    }

    public TestThis() {
              可以在构造方法中用this调用本类中的普通方法,因为this中存放的是当前类的地址
              this.a();
    }

    public TestThis(int a) {
        this();    
               //this.a指向类中的成员变量a ,a指的是传入的形式参数a。
        this.a = a;
    }

    public TestThis(int a, int b) {
       this(a);
        this.b = b;
    }

    public TestThis(int a, int b, int c) {
        this(a,b);
        this.c = c;
        System.out.println(this);
    }

    public static void main(String[] args) {
        TestThis testThis = new TestThis();
        testThis.a();
        System.out.println("对象1"+testThis);

    }
}                
构造方法中,this总是指向正要初始化的对象。

    示例:
public class TestThis {
    int a;
    int b;
    int c;
    void a(){
        System.out.println("指向调用该方法的对象1"+this);
    }

    public TestThis() {
        this.a();
        System.out.println("正要初始化的对象"+this);
    }

    public TestThis(int a) {
        this();//调用无参构造器且必须位于第一行
        this.a = a;
    }

    public TestThis(int a, int b) {
       this(a); 调用有参构造器且必须位于第一行
       this.b = b;
    }

    public TestThis(int a, int b, int c) {
        this(a,b);
        this.c = c;
        System.out.println(this);
    }

    public static void main(String[] args) {
        TestThis testThis1 = new TestThis();
        System.out.println("正要初始化的对象"+testThis1);


    }
}


#java基础知识#
全部评论

相关推荐

purcoter:虚拟货币预测正确率百分之99,还要找工作干嘛,不早就财富自由了
点赞 评论 收藏
分享
评论
3
1
分享

创作者周榜

更多
牛客网
牛客企业服务