在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
热门推荐
3 祝福语简短的微信
10 幼儿祝福语大全简短贺卡
11 感谢教官文案祝福语简短
12 鼠年同事祝福语简短创意
13 元旦祝福语 简短独特群发
14 妈咪跟我生日祝福语简短
15 给儿子新婚祝福语简短
16 伴娘祝福语长文案简短
17 恭喜高考完祝福语简短
18 生日祝福语送老公简短