Java构造子类对象时构造方法的调用顺序
子类构造对象时,首先调用超类的构造方法,所以首先被执行的是最远超类的构造方法!
举个例子吧:
package gl2;
public class Person {
public int age;
public String name;
public Person(){}
public Person(int age1,String name1){
age=age1;
name=name1;
}
public void MessageShow(){
System.out.println(age);
System.out.println(name);
}
}
package gl2;
public class Student extends Person{
int SchoolId;
public Student(int SchoolId1,int age2,String name2){
SchoolId=SchoolId1;
age=age2;
name=name2;
}
public void MessageShow(){
System.out.println(SchoolId);
System.out.println(age);
System.out.println(name);
}
}
package gl2;
public class Main {
public static void main(String args[]){
Person stu1=new Person(10,"龚雷");
Student stu2=new Student(201902185,18,"朱芊");
stu1.MessageShow();
stu2.MessageShow();
}
}
他的输出结果为
但是如果把Person类中的无参构造方法该为:
public Person(){
System.out.println("CSDN还不错!");
}
结果就变为:
希望大家能够注意一下!
让我们一起好好学java吧!