簡體   English   中英

以下程序中this(1)和this(2)的目的是什么?

[英]what is the purpose of this(1) & this(2) in the following program?

在下面的程序中,我已經使用this(1)和this(2)來使用this(1)和this(2)的目的是什么,我還想知道這是關鍵字還是方法? Java編程語言。

class Const
{
    Const()
    {
        this(1);
        System.out.println(1);

    }
    Const(int x)
    {
        System.out.println(2);
    }
}
class const1 extends Const
{
    int a;
    const1()
    {
        this(8);
        System.out.println(3);

    }
        const1(int x)
    {

        System.out.println(4);

    }
    public static void main(String s[])
    {
        new const1();
    }
}

這些是備用構造函數調用 他們在同一類中調用另一個構造函數。 這允許多個構造函數為相同的行為共享相同的代碼。 沒有它,您有時會被迫重復自己。

例如:

Const()
{
    this(1);
    ...
}

用實際參數“ 1”調用此構造函數:

Const(int x) { ... }

您可以類似的方式使用關鍵字super()來調用超類構造函數。

根據Java語言規范8.8.7.1,顯式構造函數調用

顯式構造函數調用語句可以分為兩種:

備用構造函數調用以關鍵字this(可能以顯式類型參數開頭)開頭。 它們用於調用同一類的備用構造函數。

超類構造函數的調用以關鍵字super(可能以顯式類型參數開頭)或Primary表達式開始。 它們用於調用直接超類的構造函數。

如果在構造函數內部使用this()則實際上是用來調用同一類的另一個構造函數。 如果保留重載的構造函數,這將特別有用。

public class Rectangle {
  private int x, y;
  private int width, height;

  public Rectangle() {
     this(0, 0, 0, 0);
  }
  public Rectangle(int width, int height) {
      this(0, 0, width, height);
  }
  public Rectangle(int x, int y, int width, int height) {
      this.x = x;
      this.y = y;
      this.width = width;
      this.height = height;
  }
...
}

請記住,如果使用 this()super()則必須是構造函數中的第一條語句。 因此,它們不能在構造函數中一起使用。

this ,如果一個方法體內用於將指在其上調用該方法的當前實例。

閱讀有關課程和super的Oracle教程。

這類似於為方法創建重載,因此它們模擬具有“可選”參數,例如:

DoStuff(int x, int y)
{
    //Stuff
}

DoStuff(int x)
{
    DoStuff(x, x);
}

除非您在構造函數中執行此操作(如果它們未傳遞值,則使用值1)。 為了回答這個問題, this調用了對象的構造函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM