构造方法: 方法名是类名([参数列表]){}
特点1: 构造方法没有返回值部分, void 不能有,不允许 final 和 static 修饰
public class Fourth {
//特点1:构造方法没有返回值部分, void 不能有,不允许 final 和 static 修饰
int age;
String name;
String mobile;
String address;
Fourth(int a,String n,String m,String add){
}
public static void main(String[] args) {
}
}
特点2: 一个类中默认有无参构造方法,当定义了一个有参数构造方法时,则默认无参构造方法隐藏
public class Fourth {
int age;
String name;
String mobile;
String address;
Fourth(int a,String n,String m,String add){//有参
}
Fourth(int a,String n){
}
public static void main(String[] args) {
Fourth a = new Fourth();//错误
Fourth a = new Fourth(18,"lihua","176*****715","中国");//正确
}
}
特点3: 一个类中根据需要可以定义多个构造方法,这是重载的体现
public class Fourth {
int age;
String name;
String mobile;
String address;
Fourth(int a,String n,String m,String add){
}
Fourth(int a,String n){
}
public static void main(String[] args) {
}
}
特点4: 为了简化代码,类中构造方法可以互相调用,this(实参列表),但必须置于构造方法有效代码第一行
public class Fourth {
//为了简化代码,类中构造方法可以互相调用,this(实参列表),但必须置于构造方法有效代码第一行
int age;
String name;
String mobile;
String address;
Fourth(int a,String n,String m,String add){//有参
this(a, n);//调用下面构造方法
// age = a;
// name = n;
mobile = m;
address = add;
//上面四行代码就是为成员变量赋值的过程
}
Fourth(int a,String n){
age = a;
name = n;
}
public static void main(String[] args) {
//构造方法使用new来调用
Fourth a = new Fourth(18,"lihua","176*****715","中国");
Fourth b = new Fourth(13,"xiaoming","132*****765","中国");
System.out.println(a.name);
System.out.println(b.address);
Fourth c = new Fourth(18,"光头强");
System.out.println(c.name);
}
}