在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 妈妈生日祝福语简短励志