Java构造函数的目的是什么?
Java中的构造函数在语法上类似于方法。区别在于构造函数的名称与类名称相同,并且没有返回类型。您无需调用在实例化时隐式调用的构造函数。
构造函数的主要目的是初始化类的实例变量。有两种类型的构造函数-
参数化构造函数-接受参数。通常,使用此方法,可以使用实例化时指定的值动态初始化实例变量。
public class Sample{
Int i;
public sample(int i){
this.i = i;
}
}默认构造函数-不接受任何参数。通常,使用此方法可以初始化具有固定值的实例变量。
public class Sample{
Int i;
public sample(){
this.i = 20;
}
}如果您不提供任何构造函数,则Java编译器将代表您编写一个(默认构造函数),并使用默认值初始化实例变量,例如,0表示整数,null表示String,0.0表示float等。
示例
在下面的示例中,Student类具有两个私有变量age和name。在此,使用参数化和默认构造函数。
从main方法,我们使用两个构造函数实例化类-
import java.util.Scanner;
public class StudentData {
private String name;
private int age;
//参数化的构造函数
public StudentData(String name, int age){
this.name =name;
this.age = age;
}
//默认构造函数
public StudentData(){
this.name = "Krishna";
this.age = 20;
}
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[]) {
//从用户读取值
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 参数化的构造函数
System.out.println("Display method of 参数化的构造函数: ");
new StudentData(name, age).display();
//Calling the 默认构造函数
System.out.println("Display method of 默认构造函数: ");
new StudentData().display();
}
}输出结果
Enter the name of the student: Raju Enter the age of the student: 19 Display method of 参数化的构造函数: Name of the Student: Raju Age of the Student: 19 Display method of 默认构造函数: Name of the Student: Krishna Age of the Student: 20