在Java的建構函式中,我們能否呼叫“this”關鍵字的方法?


Java中的“this”關鍵字用作對當前物件的引用,在例項方法或建構函式中使用。使用this,您可以引用類的成員,例如建構函式、變數和方法。

從建構函式中使用this關鍵字呼叫方法

是的,如前所述,我們可以從例項方法或建構函式中呼叫類的所有成員(方法、變數和建構函式)。

示例

在下面的Java程式中,Student類包含兩個私有變數name和age以及setter方法,還有一個接受這兩個值的帶引數的建構函式。

在建構函式中,我們透過分別向它們傳遞獲得的name和age值,使用“this”關鍵字呼叫setName()setAge()方法

在main方法中,我們從使用者讀取name和age值,並透過傳遞它們來呼叫建構函式。然後,我們使用display()方法顯示例項變數name和class的值。

public class Student {
   private String name;
   private int age;
   public Student(String name, int age){
      this.setName(name);
      this.setAge(age);
   }
   public void setName(String name) {
      this.name = name;
   }
   public void setAge(int age) {
      this.age = age;
   }
   public void display(){
      System.out.println("Name of the Student: "+this.name );
      System.out.println("Age of the Student: "+this.age );
   }
   public static void main(String args[]) {
      //Reading values from user
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the name of the student: ");
      String name = sc.nextLine();
      System.out.println("Enter the age of the student: ");
      int age = sc.nextInt();
      //Calling the constructor that accepts both values
      new Student(name, age).display();
   }
}

輸出

Rohan
Enter the age of the student:
18
Name of the Student: Rohan
Age of the Student: 18

更新於:2020年6月29日

6000+ 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.