• 初探java中this的用法


    一般this在各类语言中都表示“调用当前函数的对象”,java中也存在这种用法:

     1 public class Leaf {
     2     int i = 0;
     3     Leaf increment(){
     4         i++;
     5         return this;    //this指代调用increment()函数的对象
     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 
    15 }
    16 //////////out put///////////
    17 //i = 3

    在上面的代码中,我们在main()函数里首先定义了Leaf类的一个对象:x 。然后通过这个对象来调用increment()方法, 在这个increment()方法中返回了this--也就是指代调用它的当前对象x (通过这种方式就实现了链式表达式的效果)。

    我们通过x.increment()来表示通过x来调用increment()函数,实际上在java语言内部这个函数的调用形式是这样子的:

    Leaf.increment(x);

    当然,这种转换只存在与语言内部,而不能这样写码。

    另外一种情况是在构造函数中调用构造函数时,this指代一个构造函数,来看一个简单的例子:

     1 public class Flower {
     2     int petalCount = 0;
     3     String s = "initial value";
     4     Flower(int petals){
     5         petalCount = petals;
     6         System.out.println("Constructor w/ int arg only, petalCount = " + petalCount);
     7     }
     8     
     9     Flower(String ss){
    10         System.out.println("Constructor w/ string arg only, s = " + ss);
    11         s = ss;
    12     }
    13     
    14     Flower(String s, int petals){
    15         this(petals);    //这里的"this"指代的Flower构造器
    16         this.s = s;
    17         System.out.println("string and int args");
    18     }
    19     
    20     Flower(){
    21         this("hi", 47);    //这里的"this"指代的Flower构造器
    22         System.out.println("default (no args)");
    23     }
    24     public static void main(String[] args) {
    25         // TODO Auto-generated method stub
    26         new Flower();
    27     }
    28 }
    29 ////////Out put/////////////
    30 //Constructor w/ int arg only, petalCount = 47
    31 //string and int args
    32 //default (no args)

    Flower类有四个构造函数,在这写构造函数内部的this表示也是Flower类的构造函数,而且this()中的参数的个数也指代对应的构造函数,这样就实现了在构造函数中调用其他的构造函数。

    但是需要注意的一点就是:虽然我们可以通过this在一个构造函数中调用另一个构造函数,但是我们顶多只能用这种方法调用一次,而且对另一个构造函数的调用动作必须置于最起始处,否则编译器会发出错误消息。比方说,下面这样是不行的:

    Flower(String s, int petals){
            this(petals);
            this(s);  //error! 顶多只能调用this()一次。
        }
  • 相关阅读:
    多表查询,连表查询
    mysql数据概念难点
    mysql练习题
    linux下 redis
    nginx安装
    八皇后问题 OpenJ_Bailian
    Prime Ring Problem hdu-1016 DFS
    Oil Deposits hdu-1241 DFS
    Highways
    畅通工程再续
  • 原文地址:https://www.cnblogs.com/MockingBirdHome/p/3437211.html
Copyright © 2020-2023  润新知