甲构造用于创建时初始化对象。从语法上讲,它类似于一种方法。区别在于,构造函数的名称与其类相同,并且没有返回类型。
无需显式调用构造函数,这些构造函数会在实例化时自动调用。
要记住的规则
在定义构造函数时,应牢记以下几点。构造函数没有返回类型。
构造函数的名称与类的名称相同。
构造函数不能是抽象的,最终的,静态的和同步的。
您可以将访问说明符public,protected和private与构造函数一起使用。
示例
以下Java程序演示了构造函数的创建。public class Student {
public String name;
public int age;
public Student(){
this.name = "Raju";
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[]) {
new Student().display();
}
}
输出结果Name of the Student: Raju
Age of the Student: 20