如何在 Java 中建立引數化建構函式?
建構函式類似於方法,它在建立類物件時被呼叫,通常用來初始化類的例項變數。建構函式的名稱與其類相同,並且沒有返回型別。
建構函式有兩種型別:引數化建構函式和無引數建構函式。
引數化建構函式
引數化建構函式接受引數,可以用它們來初始化例項變數。使用引數化建構函式,你可以在例項化類時使用不同的值動態初始化類變數。
示例
public class StudentData {
private String name;
private int age;
public StudentData(String name, int age){
this.name = name;
this.age = age;
}
public StudentData(){
this(null, 0);
}
public StudentData(String name) {
this(name, 0);
}
public StudentData(int age) {
this(null, 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 constructor that accepts both values
System.out.println("Display method of constructor that accepts both values: ");
new StudentData(name, age).display();
System.out.println(" ");
//Calling the constructor that accepts name
System.out.println("Display method of constructor that accepts only name: ");
new StudentData(name).display();
System.out.println(" ");
//Calling the constructor that accepts age
System.out.println("Display method of constructor that accepts only age: ");
new StudentData(age).display();
System.out.println(" ");
//Calling the default constructor
System.out.println("Display method of default constructor: ");
new StudentData().display();
}
}輸出
Enter the name of the student: Krishna Enter the age of the student: 22 Display method of constructor that accepts both values: Name of the Student: Krishna Age of the Student: 22 Display method of constructor that accepts only name: Name of the Student: Krishna Age of the Student: 0 Display method of constructor that accepts only age: Name of the Student: null Age of the Student: 22
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP