使用建構函式初始化 Java 中的例項變數的類


在 Java 中,一個類包含用於初始化例項變數的建構函式。當建立類物件時,會呼叫此建構函式。

演示這一情況的程式如下 −

示例

 現場演示

class Student {
   private int rno;
   private String name;
   public Student(int r, String n) {
      rno = r;
      name = n;
   }
   public void display() {
      System.out.println("Roll Number: " + rno);
      System.out.println("Name: " + name);
   }
}
public class Demo {
   public static void main(String[] args) {
      Student s = new Student(173, "Susan");
      s.display();
   }
}

以上程式的輸出如下 −

Roll Number: 173
Name: Susan

現在讓我們來了解一下上面的程式。

建立 Student 類,其中包含資料成員 rno、name。建構函式 Student() 初始化 rno 和 name。成員函式 display() 顯示 rno 和 name 的值。演示此過程的程式碼片段如下

class Student {
   private int rno;
   private String name;
   public Student(int r, String n) {
      rno = r;
      name = n;
   }
   public void display() {
      System.out.println("Roll Number: " + rno);
      System.out.println("Name: " + name);
   }
}

在 main() 方法中,使用值 101 和“John”建立類 Student 的物件 s。然後呼叫 display() 方法。演示此過程的程式碼片段如下

public class Demo {
   public static void main(String[] args) {
      Student s = new Student(173, "Susan");
      s.display();
   }
}

更新於: 2020 年 6 月 30 日

11K+ 瀏覽次數

開啟你的職業生涯

完成課程以獲得認證

開始
廣告