java入门-面向对象基础(this关键字)

1:this关键字是什么?

this 关键字是一个变量,可以在方法中使用,用来拿到当前对象,那个对象调用方法,this就指向哪个对象,也就是拿到哪个对象

2.this关键字在实际开发中常用来干什么?

用来解决对象的成员变量和方法内部变量的名称一样时,导致的访问冲突的问题。

eg:在Test中调用thiskey对象及其方法:

Test:

package Key;

public class Test {
    public static void main(String[] args) {
        thiskey s=new thiskey();
        System.out.println(s);//输出的s 在堆内存中创建的的keythis对象地址
        s.PintThis();//调用方法时,先将自己在堆内存中创建的keythis对象地址传给方法中的this
        System.out.println("--------------------------------------");
        thiskey s2=new thiskey();
        System.out.println(s2);
        s2.PintThis();
        s.PintThis();

        //测试
        thiskey test=new thiskey();
        test.score=200;//访问当前thiskey对象前变量
        test.printPass(300);

    }
}

thiskey:

package Key;

public class thiskey {//类
    double score;//成员变量score
    public void PintThis() {  //thiskey类中的方法   //注意不能是static
        //认识this:this是一个变量,可以用在方法中,来拿到当前对象
        System.out.println(this);

    }
    public void printPass(double score){//此处score即this.score
        if(this.score>score){//注意score指的是从方法中的形参获得到的,而this.score指的是上面的成员变量score
            System.out.println("successful");
            System.out.println(this.score);

        }
        else{
            System.out.println("失败~"+this.score);
        }
    }


}

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

半截詩

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值