在Java中创建构造函数的规则是什么?
甲构造用于创建时初始化对象。从语法上讲,它类似于一种方法。区别在于,构造函数的名称与其类相同,并且没有返回类型。
无需显式调用构造函数,这些构造函数会在实例化时自动调用。
要记住的规则
在定义构造函数时,应牢记以下几点。
构造函数没有返回类型。
构造函数的名称与类的名称相同。
构造函数不能是抽象的,最终的,静态的和同步的。
您可以将访问说明符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
热门推荐
10 新年门口花束祝福语简短
11 盘锦结婚祝福语大全简短
12 父母生日祝福语 简短独特
13 家庭恩爱祝福语简短英文
14 高考俄语祝福语大全简短
15 虎年祝福语 诗句唯美简短
16 生日婚礼祝福语简短精辟
17 虎年喝酒拜年祝福语简短
18 教师闺蜜祝福语简短