在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 好听的元旦简短祝福语