存在继承关系的类 加载机制及执行过程
先说结果:
1、父类静态代码块 exec...
2、子类静态代码块 exec...
3、父类代码块 exec...
4、父类无参构造函数 exec...
5、子类代码块 exec...
6、子类无参构造函数 exec...
验证:
1、新建父类Person
package com.rmk.toextends;
public class Person {
private String name;
private int age;
private String sex;
{
System.out.println("Person 代码块 exec...");
}
static {
System.out.println("Person 静态代码块 exec...");
}
public Person() {
super();
System.out.println("Person 无参构造函数 exec...");
}
public Person(String name, int age, String sex) {
super();
this.name = name;
this.age = age;
this.sex = sex;
System.out.println("Person 有参构造函数 exec...");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Person [age=" + age + ", name=" + name + ", sex=" + sex + "]";
}
}
2、新建子类XiaoMing
package com.rmk.toextends;
public class XiaoMing extends Person{
{
System.out.println("XiaoMing 代码块 exec...");
}
static {
System.out.println("XiaoMing 静态代码块 exec...");
}
public XiaoMing() {
super();
System.out.println("XiaoMing 无参构造函数 exec...");
}
public XiaoMing(String name, int age, String sex) {
super(name, age, sex);
System.out.println("XiaoMing 有参构造函数 exec...");
}
@Override
public String toString() {
return "XiaoMing [getAge()=" + getAge() + ", getName()=" + getName()
+ ", getSex()=" + getSex() + ", toString()=" + super.toString()
+ ", getClass()=" + getClass() + ", hashCode()=" + hashCode()
+ "]";
}
}
3、测试
package com.rmk.toextends;
public class TestExtends {
/**
* @param args
*/
public static void main(String[] args) {
XiaoMing xm = new XiaoMing();
// xm.setName("小明");
// xm.setAge(20);
// xm.setSex("男");
// xm.toString();
}
}
4、输出结果:
最后,大家觉得我写的不错的,可以关注下哦^v^