构造函数/方法(constructor)
参考:Java构造器(构造方法) -Java教程
1.作用:
用于初始化对象(一种特殊的方法)
__构造方法 = 对象的"出生仪式"__。 孩子一出生就要哭、要登记户口。
`new`一个对象时,构造方法就要执行——把字段初始化、注册到系统、做准备工作。
2.为什么叫“构造”函数?
在对象创建时调用它,它来提供对象的数据,即构造值,因此叫构造函数
3.规则|规定
- 构造函数名必须与其类名相同
- 构造函数必须没有显式返回类型
4.构造函数类型
- 无参数构造函数(默认构造函数)default constructor
- 参数化构造函数 (有参数)parameterized constructor
4.1.无参数构造函数(默认构造函数)
class_name(){}public class bicycle { bicycle(){ System.out.println("对象b被创建"); } //构造函数在创建对象时被调用 public static void main(String[] args) { bicycle b = new bicycle(); } } //运行结果:对象b被创建- 如果类中没有构造函数,编译器会自动创建一个默认构造函数。
- 默认构造函数根据类型为对象提供默认值,如:
0,null等
public class Student { //属性 int id; String name; //方法 void display(){ System.out.println(id +" "+ name); } public static void main(String[] args) { //创建对象s1,s2 Student s1 = new Student(); Student s2 = new Student(); //调用 s1.display(); s2.display(); } }//运行结果 0 null 0 null Process finished with exit code 0在上面的类中,代码中并没有创建任何构造函数,但编译器自动提供了一个默认构造函数。默认构造函数分别为字段:id和name分别提供了0和null值
4.2.参数化构造函数(有参数)
作用:为不同对象提供不同初始化的值
public class Student { int id; String name; void display(){ System.out.println(id +" "+ name); } //参数化构造函数 Student(int i,String n){ id = i; name = n; } public static void main(String[] args) { //创建对象s1,s2 Student s1 = new Student(123,"张三"); Student s2 = new Student(456,"李四"); s1.display(); s2.display(); } }//运行结果 123 张三 456 李四 Process finished with exit code 0