java继承的构造函数调用顺序

1、首先调用父类的无参构造函数(这个构造函数必定会被调用)

2、调用子类的无参构造函数或带参数的构造函数;


例:

1、声明抽象类爷爷--Father_of_AbstractClass

public abstract class Father_of_AbstractClass {
	
	protected Father_of_AbstractClass(){
		System.out.println("this is Father_of_AbstractClass's narg-constructor");
	}

	protected Father_of_AbstractClass(int i){
		System.out.println("this is Father_of_AbstractClass's narg-constructor");
	}
}


2、什么抽象类AbstractClass(“父字辈的类”) 继承自Father_of_AbstractClass
public abstract class AbstractClass extends Father_of_AbstractClass{
	protected int abstractField;
	

  protected AbstractClass(){
	    this.abstractField = 0;
		System.out.println("this is AbstractClass's narg-constructor,and abstractField = "+this.abstractField);
	}

	//若创建了带参的构造函数,则无参的构造函数必须显示的写出来,否则会编译不通过
	protected AbstractClass(int i){
		this.abstractField = i;
		System.out.println("this is AbstractClass's arg-constructor,and abstractField = "+this.abstractField);
	}
}


3、声明“孙字辈的类”-GrandChieldren 继承自AbstractClass

public class GrandChieldren extends AbstractClass {
    public GrandChieldren(){
    	System.out.println("this is GrandChieldren's noargs-constructor");
    }
    
    public GrandChieldren(int i){
    	System.out.println("this is GrandChieldren's arg-constructor");
    }
    
    public static void main(String args[]){
    	
    	/*
          此处输出
          this is Father_of_AbstractClass's narg-constructor
          this is AbstractClass's narg-constructor,and abstractField = 0
          this is GrandChieldren's noargs-constructor
        */
    	GrandChieldren e = new GrandChieldren();
    	
    	/*
    	 * this is Father_of_AbstractClass's narg-constructor
    	 this is AbstractClass's narg-constructor,and abstractField = 0
         this is GrandChieldren's arg-constructor
         *表明实例化子类时,
         *1、先調用父輩的無慘構造函數(递归至顶层父类),
         *2、在調用子類的構造函數,根据有无参数选择无参构造函数或带参构造函数
         */
    	GrandChieldren f = new GrandChieldren(3);
    }
}


此外,抽象类的构造函数作用:

1、可初始化成员变量;

2、为继承自它的子类所使用;子类B实例化时会自动调用父类A的默认构造函数,所以,我们最好给父类A提供一个无参数的构造函数,或者在B的构造函数中显示的调用父类A的有参构造函数。super(parameter


同时,抽象类不能被实例化,因为抽象类是抽象出来的,不存在实际的实体。所以实例化一个抽象类是没有意义的,因此面向对象程序设计机制禁止对象实例化。






你可能感兴趣的:(java)