this使用的两种情况

来源:互联网 发布:cf刷点卷软件 编辑:程序博客网 时间:2024/05/16 08:48

一、this关键字对于将当前对象传递给其他方法

/* * this关键字对于将当前对象传递给其他方法 */class Person {public void eat(Apple apple){Apple peeled=apple.getPeeled();System.out.println("eat...");}} class Apple {Apple getPeeled(){/** this关键字对于将当前对象传递给其他方法,Apple需要调用Peeler.peel()方法,它是一个外部工具类方法,* 将执行由于某种原因而必须放在Apple外部的操作。为了将其自身传递给外部方法,Apple必须使用this关键字*/return Peeler.peel(this);}     } class Peeler {static Apple peel(Apple apple){return apple;}} public class PassingThis {public static void main(String[] args) {new Person().eat(new Apple());}}

二、返回对当前对象的引用

/** * 返回当前对象的引用 * @author xieyongxue * */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 leaf=new Leaf();leaf.increment().increment().increment().print();/** 输出值:i=3*/}}
原创粉丝点击