子类在创建对象时会隐式调用父类的无参构造函数,此时若父类没有无参的构造函数就会出错,我们可以通过在子类的构造函数中使用super()来显示地调用父类的其他构造函数。
public class Hello {
public static void main(String []args){
new Children();
}
}
class Father {
public Father(int a,int b){
System.out.println("father: creator" );
}
}
class Children extends Father {
public Children(){
super (1 ,2 );
System.out.println("children: creator" );
}
}
在有子类和父类的时候,先静后动,先父后子,在用到类的时候就调用静态代码块(只声明引用不算用到类),在用到对象的时候才用到构造函数。成员属性的赋值的执行先于构造函数。
public class Hello {
public static void main(String []args){
Children.count =1 ;
System.out.println("-----------------" );
new Children();
}
}
class Father {
int b=1 ;
static {
System.out.println("father: static" );
}
public Father(){
System.out.println("father: creator" );
}
}
class Children extends Father {
static int count =0 ;
static {
System.out.println("children: static" );
}
public Children(){
System.out.println("children: creator" );
}
}