我们学习一个东西首先哟啊对这个有所理解也就是所说的概念先看下概念
概念
构造函数:
是一个特殊的函数,与类名相同,无返回值类型
每个类中都默认有一个无参的构造函数(是隐藏的)
创建对象时执行构造函数
构造函数的作用:初始化对象
创建对象时,给对象属性赋值
格式:
public 类名([参数]){
}
创建对象格式:版本2
类名 对象名 = new 构造函数();
运用案例:
public class Student {
public Student(){
}
public Student(String xh, String xm, String xb, int cj) {//有参的构造函数运用
this.xh = xh;
this.xm = xm;
this.xb = xb;
this.cj = cj;
} String xh;
String xm;
String xb;
int cj; public String getXh() {
return xh;
} public void setXh(String xh) {
this.xh = xh;
} public String getXm() {
return xm;
} public void setXm(String xm) {
this.xm = xm;
} public String getXb() {
return xb;
} public void setXb(String xb) {
this.xb = xb;
} public int getCj() {
return cj;
} public void setCj(int cj) {
this.cj = cj;
} @Override
public String toString() {
return "学号:" + xh + "\t" + "姓名:" + xm + "\t" + "性别:" + xb + "\t" + "成绩:" + cj;
}
接下来我们看测试类
public class TestStudent {
public static void main(String[] args) { Student and = new Student("1", "顾星辰", "男", 99);
System.out.println(and); Student two =new Student("2","顾一珩" , "女", 100);
System.out.println(two);
}
}