面向对象——this关键字

  this:表示当前对象的指针
       指向当前对象,表示对当前对象的调用
       用途:
       1、构造方法,当构造方法的名称跟类的成员变量的名称一样的时候,可以使用this代表当前对象
           注意:当构造方法中需要其他构造方法时,可以使用this(参数列表)调用其他构造方法,但是需要位于方法体的第一行
       2.普通方法中:
           当多个普通方法需要互相调用时,可以使用this.方法来进行调用,指的是当前对象的其他方法
       3、调用成员变量的时候如何使用:
           当方法名的参数名称跟成员变量保持一致时,使用this.变量名称 表示的是对象的值,而使用变量名称则是参数的值
       注意:
            this不能使用于static方法中

package com.gml;

public class ThisDemo {
    //成员变量
    String name;
    int age;
    int height;
    double weight;

    //构造器,构造方法
    public ThisDemo() {

    }

    public ThisDemo(String name,int age,int height,double weight){
        this.name=name;
        this.age=age;
        this.height=height;
        this.weight=weight;
    }

    public static void main(String[] args) {
        ThisDemo td = new ThisDemo("阿龙",18,170,110.5);
        System.out.println("姓名: "+td.name);
        System.out.println("年龄: "+td.age);
        System.out.println("身高: "+td.height);
        System.out.println("体重: "+td.weight);
    }
}

package com.gml;

public class TestThis {
    int a,b,c;
    TestThis(){
        System.out.println("我好喜欢小顺子啊! ");
    }
    TestThis(int a,int b){
        this();//调用无参的构造方法,并且必须位于第一行!

        a=a;//这里都是指的局部变量而不是成员变量
        this.a = a;//这样就区分了成员变量和局部变量,这种情况占了this使用情况的大多数!
        this.b = b;
    }

    TestThis(int a,int b,int c){
        this(a,b);//调用无参的构造方法,并且必须位于第一行!
        this.c =c;
    }
    void sing(){

    }
    void chifan(){
        this.sing();//sing();
        System.out.println("小顺子喊你回家吃饭! ");
    }

    public static void main(String[] args) {
        TestThis hi = new TestThis(2,3);
        hi.chifan();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值