浅谈this关键字

如果你希望在方法的内部获得当前对象的引用。由于这个引用是由编译器“偷偷”传入的,所以吧没有标识符可以用,但是,为此有了一个专门的关键字:this。this关键字只能在方法的内部使用,表示对“调用方法的那个对象”的引用。this的方法和其他对象引用并无不同。但是,要注意,如果在方法内部调用同一个类的另一个方法,就不必用this,直接调用即可。当前方法中的this引用会自动应用于一同一类的其他方法
package com.day1.first;
public class Leaf {
int i = 0;
Leaf increment() {
i++;
return this;//表示返回当前类对象
}
public void print() {//新建一个打印的方法
System.out.println("i="+i);
}
public static void main(String[] args) {
Leaf x = new Leaf();
x.increment().increment().increment().increment().print();
//i=4,最终输出的结果。由于increment()通过this关键字返回了对当前对象的引用,所以很容易在同一条语句
//里对同一个对象执行多次操作
}

}

this关键字对于将当前对象传递给其他方法实例:

package com.day1.first;
class Person {//创建一个人类;
public void eat(Apple apple) {
Apple peeled = apple.getPeeled();
System.out.println("Yummy");
}
}
class Peeler{//创建Peeler类
static Apple peel(Apple apple){//创建一个剥苹果的静态方法
return apple;//返回一个apple对象
}
}
class Apple{//创建一个Apple类。
Apple getPeeled() {//获取剥苹果皮的方法返回当前的类对象,且打算将自身传递给外部方法。
return Peeler.peel(this);
}
}
public class PassingThis {
public static void main(String[] args) {
new Person().eat(new Apple());
}
}

输出:Yummy

Apple 需要调用Peeler.peel(),他是一个外部的工具方法,将执行由于某种原因而必须放在Apple外部的操作,(也许是因为该外部方法要应用于许多不同的类,而你却不想重复这些代码)。为了将其自身传递给外部方法,Apple必须使用this关键字。

总而言之,言而总之:this关键字就是---》代表当前对象的引用。(谁来调用我,我就代表谁)

啥又是当前对象的引用呢?

且看实例:

Object  obj = new    Object();

//obj:对象的引用

//new Object():对象

//Object:类

this和super的区别:

this:当前对象的引用

          调用当前类的成员变量及成员方法,

          在子类的构造方法第一行调用子类其他构造方法

super:子类对象的父类引用

        调用的父类的成员变量及父类的成员方法,

        在子类构造方法的第一行调用父类的构造方法

猜你喜欢

转载自blog.csdn.net/weixin_42698882/article/details/81051338