如何在 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