参数化构造函数在 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP