Java语言学习细节之构造方法调用浅谈


    在学习JAVA过程中,必须要了解这些基本的东西才能对读代码少些困惑,而这些细节是新手必须注意的。

    总结:初始化的顺序为:先初始化父类的静态代码——>初始化子类的静态代码——>创建实例时,如果不创建实例,则后面的不执行)初始化父类的非静态代码——>初始化父类构造函数——>初始化子类非静态代码——>初始化子类构造函数子类继承父类会先初始化父类,调用父类的构造函数。

    子类的构造方法的第一条语句就是调用父类的没有参数的构造方法,如果你没有写出这条语句java虚拟机就会默认的调用,如果你显示的写了这条语句,就一定要写在构造方法中的第一条语句,不然会报错。

    原理简述:只有在构造方法中调用了父类的构造方法才能继承父类的相关属性和方法,要不然子类从哪里继承父类的属性和方法,在实例化子类的时候又没有和父类有任何关系。

    子类的构造函数默认调用和这个构造函数参数一致的父类构造函数,除非在此子类构造函数的第一行显式调用父类的某个构造函数。

类Example1
class father{
    int x=0,y=0;
    father(){
        System.out.println("now is in father's constructor");
    }
    father(int x,int y){
        this.x=x;
        this.y=y;
    }
    public void print(){
        System.out.println("x="+x+";y="+y);
    }
}
class son extends father{
    son(){
        System.out.println("now is in son's constructor");
    }
    son(int x,int y){
        super(x,y);//改变x,y,的值,若无super(x,y),则默认调用father()
    }
    public void print(){
        super.print();
        System.out.println("my name is son!");
    }
}
public class Example1 {
public static void main (String[] args){
    son s=new son();//实例化构造的时候从父类开始调用
    s.print();//此处不是构造,是调用
    son f=new son(10,20);

    f.print();
}
}
运行结果::


now is in father's constructor
now is in son's constructor
x=0;y=0
my name is son!
x=10;y=20
my name is son!

类Example2:
class father{
    int x=0,y=0;
    father(){
        System.out.println("now is in father's constructor");
    }
    father(int x,int y){
        this.x=x;
        this.y=y;
    }

    public void print(){
        System.out.println("x="+x+";y="+y);
    }
}
class son extends father{
    son(){
        System.out.println("now is in son's constructor");
    }
    son(int x,int y){
        //改变x,y,的值
        System.out.println("s213");
    }
    public void print(){
        //引用父类的print函数
        System.out.println("my name is son!");
    }
}
public class Example2 {
public static void main (String[] args){
    son s=new son();//实例化构造的时候从父类开始调用
    s.print();//此处不是构造,是调用, oh,yeah!
    son f=new son(10,20);//先调用父类的father(){System.out.println("now is in }
   //而不是father(int x,int y){this.x=x;this.y=y;}

    f.print();
}
}
运行结果
now is in father's constructor
now is in son's constructor
my name is son!
now is in father's constructor
s213


    对比这两个类的注释和结果相信你就会明白了。

相关内容