java执行系统默认的构造方法时会给所有参数赋值为0或null
如果构建了带参数的构造方法 , 同样要定义<对象名>() , 也就是空参的构造方法 , 否则会产生错误
在同一类下重载构造方法时可以用 : this(<参数>)来替代
public class hello {
int value;
String str;
public static void main(String[] args) {
hello h = new hello(1);
h.say();
}
public hello(){ //初始化
this.str = "hello";
this.value = 0;
}
public hello(int value){ //有特定值的 , 进行重载的
this(value , "hi");
}
public hello(int value, String str){
this.str = str;
this.value = value;
}
public void say() {
System.out.println(this.str);
}
}
结果为hi
子类继承父类构造方法时
子类继承父类的构造参数并在继承的构造方法中构造这些参数
public class hello {
public static void main(String[] args) {
Point3d p3d = new Point3d(1,2,3);
System.out.println(p3d.x + p3d.y + p3d.z);
}
}
class Point{
int x,y;
Point(int x,int y){
this.x=x;
this.y=y;
}
}
class Point3d extends Point{//x,y,z
int z;
Point3d(int x, int y,int z){
super(x,y);
this.z=z;
}
}
结果为6
特别的 , 所有子类的构造方法都会要求引用父类的构造方法也就是super() , 如果父类没有对应的构造方法就会报错