this关键字只能在方法内使用,并且只能在该方法的第一行,表示的是“调用方法的那个对象的引用”,


this是链式编程的关键

static域将在类加载到虚拟机的时候立马去执行,且只执行一次

1>this是链式编程的关键

  1. public class Leaf {
  2. int i = 0;
  3. Leaf increment() {
  4. i++;
  5. return this;
  6. }
  7. void print() {
  8. System.out.println("i = " + i);
  9. }
  10. public static void main(String[] args) {
  11. Leaf x = new Leaf();
  12. x.increment().increment().increment().print();
  13. }
  14. }

2>this关键字可以作为当前实例传递给其他的方法

  1. class Person {
  2. public void eat(Apple apple) {
  3. Apple peeled = apple.getPeeled();
  4. System.out.println("Yummy");
  5. }
  6. }
  7. class Peeler {
  8. static Apple peel(Apple apple) {
  9. // ... remove peel
  10. return apple; // Peeled
  11. }
  12. }
  13. class Apple {
  14. Apple getPeeled() { return Peeler.peel(this); }
  15. }
  16. public class PassingThis {
  17. public static void main(String[] args) {
  18. new Person().eat(new Apple());
  19. }
  20. }

3>在构造器中调用其他构造器的时候 使用this,但不支持在多个构造其中一起使用(可能会造成死循环)

4>this与static的区别:this属于实例,static属于类

  1. static方法中不可以调用非静态方法,反之可以;
  2. static在没有创建任何对象的前提下,仅仅通过类本身来调用static方法或域