构造函数的意义在于可以创建方法对象(new)时就传参。
如普通函数需要变量名.属性名赋值时,构造函数已经解决掉赋值问题了。
构造方法没有返回值类型,创建对象一结束方法就执行完毕,也没有返回值。
构造函数的方法名需要和类名相同
一个类中可以有多个构造方法,多个构造方法是以重载的形式存在的
构造方法是可以被private修饰的,作用:其他程序无法创建该类的对象。最好添加getxxx和setxxx封装
构造方法的定义:
注意:
1.构造函数的方法名需要和类名相同
如类名person,下面的构造函数是相同的
public class person(){
private string name;
private int age;
第一种:没有参数的构造函数
public person(){
system.out.in(“啦啦啦啦”);
}
第二种:有参数的构造函数 this代表本类对象,也就是本文中的person类
public person(String name,int age){
this.name=name;
this.age=age;
因为两个person方法名字相同,但因为第二个函数有形参,所以涉及到方法重载,(参数的类型,位置,数量不同),解决这个方法用到之前的this关键字,解决成员变量和局部变量重名问题。
}
第三种:如果我们没有写构造函数,但在测试类中却能new一个新对象,是因为系统默认一个构造函数
}
如:public person(){
super();
}
测试:构造方法只能调一次,但一般方法可以调取多次
public class Cs_d {
public static void main(String[] args) {
//new一次调一次
Demo01 d=new Demo01();也就是new对象的时候就调用了构造构造方法,{对象名.方法名()}获取了构造方法的全部内容,并且可以用构造方法传参
Demo01 d1=new Demo01("司南",23);
只能敷一次值,如果需要更改需要用封装的setXXX来修改
System.out.println(d.getName()+" ... "+d.getAge());
输出则是用普通方法调用
System.out.println(d1.getName()+" ... "+d1.getAge());
普通类可以一直用
d.person();
来调用
}
}
构造函数:
运行时,先走父类方法,再走子类方法。
this关键字:
this代表本类对象
this(参数列表);
代表的是构造方法里的
this.调取普通方法和属性
this(参数列表);在构造方法中必须放在第一行执行
public class student(){
string name;
int age;
调取有参数的构造方法给赋值
this("张三",23);
public student(String name,int age){
两个this等价的,也就等于this.name=张三;this.age=12;
这里的this就等于本类对象(成员变量)name=张三;age=12;
this.name=name;
this.age=age;
}
}
测试:因为this在里面调用赋值,所以我们只需要输出即可
public class Cs_student {
public static void main(String[] args) {
Student stu=new Student();
Student stu1=new Student();
//对象名的方法名
stu1.Student();
System.out.println(stu.getName()+"..."+stu.getAge());
}
}
supper关键字
调用本类中的构造方法
this(实参列表);
调用父类中的空参数构造方法
super();
调用父类中的有参数构造方法
super(实参列表);
如果出现this和super在同一个类里面,不能放在一起,需要将super放在第二个方法中,this放在第一个方法里,this和supper都需要放在方法中的第一行。
public class Fu { //父类也有super();调取父类构造object==隐式super object //父类构造函数 public Fu(){ System.out.println("这是父类无参构造"); } public Fu(String name){ System.out.println("这是父类有参构造"); } } public class Zi extends Fu { public Zi(){ //每一个构造都有一个默认的super(); //必须放在第一行 //super("aa"); //this(1); System.out.println("这是子类的无参构造"); } public Zi(int age){ //super("aa");如果在上面有this的情况下,第一行就没有super,就去调取第二个构造函数的super System.out.println("这是子类的有参构造"); } } public class Demo03 { public static void main(String[] args) { //先走zi();走的zi类无参 //先走父类构造,再走子类构造 Zi zi=new Zi(); } }