如何使用 Java 创建默认构造函数?
默认构造函数(无参数构造函数)
无参数构造函数不接受任何参数,它用其各自的默认值(即对象为 null,浮点数和双精度数为 0.0,布尔值为 false,字节、短整型、整型和长整型为 0)为类变量实例化。
无需显式调用构造函数,它们在实例化时自动调用。
需要记住的规则
定义构造函数时,应记住以下几点。
构造函数没有返回类型。
构造函数的名称与类名称相同。
构造函数不能为抽象、final、static 和 Synchronized。
可对构造函数使用访问修饰符 public、protected 和 private。
示例
class NumberValue {
private int num;
public void display() {
System.out.println("The number is: " + num);
}
}
public class Demo {
public static void main(String[] args) {
NumberValue obj = new NumberValue();
obj.display();
}
}输出
The number is: 0
示例
public class Student {
public final String name;
public final 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
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP