this是什么呢?
this就是一个变量,用在方法中,可以拿到当前类的对象。
我们看下图所示代码,通过代码来体会这句话到底是什么意思。哪一个对象调用方法,方法中的this就是哪一个对象

上面代码运行结果如下

this有什么用呢?
通过this在方法中可以访问本类对象的成员变量。我们看下图代码,分析打印结果是多少:
StudentInfo文件:
package com.learn.test.oop;
public class StudentInfo {
double score;
public void printIsPass(double score){
if(this.score > score){
System.out.println("Pass");
}else {
System.out.println("Fail");
}
}
}
ObjectOrientDemo文件
package com.learn.test.oop;
public class ObjectOrientedDemo {
public static void main(String[] args) {
StudentInfo si = new StudentInfo();
si.score = 200;
si.printIsPass(180);
}
}
分析上面的代码si.score=200,调用方法printPass方法时,方法中的this.score也是325; 而方法中的参数score接收的是250。执行结果是
关于this关键字我们就学习到这里,重点记住这句话:哪一个对象调用方法方法中的this就是哪一个对象

3863

被折叠的 条评论
为什么被折叠?



