zl程序教程

您现在的位置是:首页 >  其它

当前栏目

this

this
2023-09-27 14:23:51 时间

一:this 将对象传递给其它方法

package object;

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

 二:this 可以调用构造器,单不能调用两个,此外,must 将构造器调用置于最起始处,否则编译器会报错

这个例子也展示了this的另一种用法 this.s   ;  除构造器外编译器禁止在其它任何方法中调用构造器

//: object/Flower.java

package object;

import static net.mindview.util.Print.*;
public class Flower{
    int petalCount = 0;
    String s = "initial value";
    Flower(int petals)
    {
        print("Constructor w/ int arg only, petalCount ="+petals);
    }
    Flower(String ss)
    {
        print("Constructor w/ String args only, s = "+ ss);
        s = ss;
    }
    Flower (String s, int petals)
    {
        this(petals);
        //! this(s); //Can't call two
        this.s=s; //Another use of "this"
        print("String & int args");
    }
    Flower()
    {
        this("hi",47);
        print("default constructor (no args)");
    }
    void printPetalCount()
    {
        //! this(11); //Not inside non-constructor!
        print("petalCount = " + petalCount+ " s = "+ s);
    }
    public static void main(String[] args)
    {
        Flower x = new Flower();
        x.printPetalCount();
    }
}/** output;
Constructor w/ int arg only, petalCount =47
String & int args
default constructor (no args)
petalCount = 0 s = hi
*///:~