this关键字、this()、super()

对于下面的代码怎么区分是哪个对象调用当前方法:

Class Banana {
    void peel(int i);
}
publci Class BananaPeel {
    public static void main(String[] args) {
        Banana a = new Banana();
        Banana b = new Banana();
        a.peel(1);
        b.peel(2);
    }
}

编译器会自动把“所操作对象的引用”作为第一个参数传递给peel(),所以上述两个方法的调用就变成如下形式:

Banana.peel(a, 1);

Banana.peel(b, 2);

this只能在方法内部使用,表示对“调用方法的那个对象”的引用。

如果在方法内部调用同一个类的另一个方法,就不必使用this,直接调用即可。

对于下面的代码:

public class Apricot {
    void pick();
    void pit() { pick();...}
}

在pit()内部,可以写this.pick(),但没不要。编译器会自动添加。

当需要返回对当前对象的引用时,常常在return语句中这样写:

public Class Leaf {
    int i = 0;
    Leaf increment() {
        i++;
        return this;
    }
    void print() {
        System.out.println("i = " + i);
    }
    public static void main(String[] args) {
        Leaf x = new Leaf();
        x.increment().increment().increment().print();
    }
}
//结果i  = 3

由于increment()通过this关键字返回对当前对象的引用,所以很容易在一条语句里对同一个对象执行多次操作。

this关键字对于将当前对象传递给其他方法也很有用:

public class Test1 {

    public static void main(String[] args) {
        new Person().eat(new Apple());
    }

}
class Person {
    public void eat(Apple apple) {
        apple.getPeeled();
        System.out.println("eat");
    }
}
class Peeler {
    static Apple peel(Apple apple) {
        return apple;
    }
}
class Apple {
    Apple getPeeled() {
        return Peeler.peel(this);
    }
}

Apple需要调用Peeler.peel()方法,它是一个外部的工具方法,将执行由于某种原因而必须放在Apple外部的操作,为了将其自身传递给外部方法,Apple必须使用this关键字。

this关键字的作用:

1.调用本类中的成员变量。

2.调用本类中的其他构造方法,调用时要放在构造方法的首行,且只能调用一次。

3.返回对象的值。

1.调用成员变量例子:

public class Student {
    String name;
    private void setName(String name) {
        this.name = name;
    }
}

2.调用构造方法例子:

public class Flower {
    int a = 0;
    String s = "";
    public Flower(int a) {
        this.a = a;
    }
    public Flower(String s) {
        this.s = s;
    }
    public Flower(String s, int a) {
        this(s);
     //   this(a);编译错误
        this.a = a;
    }
}

3.返回对象的值的例子可以看上面的return this的例子。

4.在类方法中不能有this关键字,直接调用类方法即可。

super()

      1:特殊变量super,提供了对父类的访问。
      2:可以使用super访问父类被子类隐藏的变量或覆盖的方法。
      3:每个子类构造方法的第一条语句,都是隐含地调用super(),如果父类没有这种形式的构造函数,那么在编译的时候就会报错。
      4:构造是不能被继承的。

原文地址:https://www.cnblogs.com/cing/p/8379242.html