zoukankan      html  css  js  c++  java
  • this

    一: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
    *///:~
  • 相关阅读:
    [文字雲產生器] Tagxedo 把文字串成雲、變成畫,印在 T-Shirt、馬克杯、詩袋….
    python学习(六)
    根据URL地址获取域名
    python学习(五)
    Linux下查看Mysql数据库端口的方法
    python学习(四)
    python学习(三)
    python学习(二)
    Java String删除字符串中间的某部分
    Spring的一个入门例子
  • 原文地址:https://www.cnblogs.com/jiangfeilong/p/10055089.html
Copyright © 2011-2022 走看看