Java this keyword

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wangbingfengf98/article/details/85224315

1. The this keyword is used only for those special cases where you must explicitly use the reference to the current object.

code example: https://github.com/wangbingfeng/OnJava8-Examples/blob/master/housekeeping/Leaf.java

2. The this keyword is useful for passing the current object to another method.

code example: https://github.com/wangbingfeng/OnJava8-Examples/blob/master/housekeeping/PassingThis.java

3. Calling Constructors from Constructors use this keyword.

pay attention to the comments about this keyword in below code.

// housekeeping/Flower.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Calling constructors with "this"

public class Flower {
  int petalCount = 0;
  String s = "initial value";

  Flower(int petals) {
    petalCount = petals;
    System.out.println("Constructor w/ int arg only, petalCount= " + petalCount);
  }

  Flower(String ss) {
    System.out.println("Constructor w/ String arg 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"
    System.out.println("String & int args");
  }

  Flower() {
    this("hi", 47);
    System.out.println("no-arg constructor");
  }

  void printPetalCount() {
    // - this(11); // Not inside non-constructor!
    System.out.println("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
no-arg constructor
petalCount = 47 s = hi
*/

猜你喜欢

转载自blog.csdn.net/wangbingfengf98/article/details/85224315