this关键字只能在方法内使用,并且只能在该方法的第一行,表示的是“调用方法的那个对象的引用”,
this是链式编程的关键
static域将在类加载到虚拟机的时候立马去执行,且只执行一次
1>this是链式编程的关键
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();}}
2>this关键字可以作为当前实例传递给其他的方法
class Person {public void eat(Apple apple) {Apple peeled = apple.getPeeled();System.out.println("Yummy");}}class Peeler {static Apple peel(Apple apple) {// ... remove peelreturn apple; // Peeled}}class Apple {Apple getPeeled() { return Peeler.peel(this); }}public class PassingThis {public static void main(String[] args) {new Person().eat(new Apple());}}
3>在构造器中调用其他构造器的时候 使用this,但不支持在多个构造其中一起使用(可能会造成死循环)
4>this与static的区别:this属于实例,static属于类
在static方法中不可以调用非静态方法,反之可以;static在没有创建任何对象的前提下,仅仅通过类本身来调用static方法或域
