引數化建構函式在 Java 中的用途是什麼?
建構函式類似於方法,在建立類物件時呼叫它,通常用於初始化類的例項變數。建構函式與它們的類同名,且沒有返回型別。
有兩種型別的建構函式:引數化建構函式和無參建構函式,引數化建構函式接受引數。
建構函式的主要目的是初始化類的例項變數。使用引數化建構函式,你可以使用在例項化時指定的值動態地初始化例項變數。
public class Sample{ Int i; public sample(int i){ this.i = i; } }
示例
在以下示例中,Student 類有兩個私有變數 age 和 name。我們使用引數化建構函式從 main 方法例項化類變數 −
import java.util.Scanner; public class StudentData { private String name; private int age; //parameterized constructor public StudentData(String name, int age){ this.name =name; 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(); System.out.println(" "); //Calling the parameterized constructor new StudentData(name, age).display(); } }
輸出
Enter the name of the student: Sundar Enter the age of the student: 20 Name of the Student: Sundar Age of the Student: 20
廣告