无参的构造方法会在创建类对象时自动生成(在你没有写任何构造方法时),我们常能在资料种看到构造方法的作用时初始化对象的内容,具体时怎么初始化的,又比较模糊。下面来看一个例子
public class Student {//一个student类
String name;//姓名
int age;//年龄
public Student(String name, int age) {//有参构造,两个参数为在创建对象时需要传入的参数
this.name = name;//this.name表示当前类中的变量,等号后的name为这个构造方法中的参数。这句是赋值:把通过创建对象传入的姓名赋值给当前类,起倒初始化的作用。
this.age = age;//同上
}
public static void main(String[] args) {
Student student = new Student("张三",11);//创建student对象,并传入参数,进行初始化。这部分创建了对象,会自动调用构造方法对类对象进行初始化。
System.out.println(student.name+student.age);
}
}
- 如果该类中不写有参构造方法,就不能在创建类对象时,传入参数(默认为无参构造)。执意要传入参数,会报红。
就像这样: - 假设你创建了一个学生类,但不是所有的学生都会拥有同样的技能,可能有的会唱歌、跳舞,有的只会唱歌。为了满足能创建拥有不同能力的学生对象,就需要写不同参数的构造方法。
package com.practice;
public class Student {
String name;//姓名
String sing;//会唱歌
String dance;//会跳舞
public Student(String name, String sing,String dance) {//会唱歌、跳舞的构造方法
this.name = name;
this.sing = sing;
this.dance = dance;
}
public Student(String name, String sing) {//会唱歌的构造方法
this.name = name;
this.sing = sing;
}
public Student(String name) {//什么也不会的构造方法
this.name = name;
}
public Student() {//如果已经写了有参构造,需要用到无参构造时,需要自己写。
}
public static void main(String[] args) {
Student student1 = new Student("张三","唱歌","跳舞");//三个参数,自动第调用有三个参数的构造方法
System.out.println(student1.name+student1.sing+student1.dance+"\n");
Student student2 = new Student("李四","唱歌");//两个参数,自动调用有两个参数的构造方法(如果存在好几个有
// 两个参数的构造方法,会根据不同的参数数据类型进行调用)
System.out.println(student2.name+student2.sing+student2.dance+"\n");
Student student3 = new Student("王五");//一个参数,啥也不会
System.out.println(student3.name+student2.sing+student2.dance+"\n");
Student student4 = new Student();//无参,啥也没有
System.out.println(student4.name+student4.sing+student4.dance);
}
}
结果:
一起加油鸭~