Java虚拟机加载顺序

【※】Java虚拟机加载顺序:【※】
public class StaticBlankChild extends StaticBlankParent{
static int a = 1;
static {
a = 10;
System.out.println("Child static code");
}
public StaticBlankChild() {
System.out.println("Child constructor");
System.out.println("Child a=" + a);
}
public static void main(String[] args) {
System.out.println("***************");
StaticBlankChild c = new StaticBlankChild();
}
}
public class StaticBlankParent {
static int a = 2;
static {
a = 20;
System.out.println("Parent static code");
}
public StaticBlankParent() {
System.out.println("Parent constructor");
System.out.println("Parent var a=" + a);
}
}
执行的结果是:
Parent static code
Child static code
***************
Parent constructor
Parent var a=20
Child constructor
Child a=10
由此可以知道,我们在要加载拥有入口函数的子类之前,是要首先加载这个函数的父类的!

Java 语言是动态链接的,只有在需要的时候才去加载java类,在加载java类的时候,首先执行类里面的static代码块(先父后子),然后进入main入口函数,调用子类的构造函数,生成子类的对象,然后开始调用子类的构造函数,调用之前要是检查到父类还没实例化,前去调用父类的构造函数,保证父类实例化完毕了再去调用子类的构造函数,在子类构造函数中第一句可以用super()调用父类的构造函数感觉像是重新实例化了一个对象!
Java父子类之间转化原则:
public class StaticBlankChild extends StaticBlankParent{
static int a = 1;
static {
a = 10;
System.out.println("Child static code");
}
public StaticBlankChild() {
System.out.println("Child constructor");
System.out.println("Child a=" + a);
}
public static void main(String[] args) {
System.out.println("***************");
StaticBlankChild child = new StaticBlankChild();
StaticBlankParent parent = new StaticBlankParent();
child = (StaticBlankChild) parent; // ClassCastException
parent = child; // OK
}
}
public class StaticBlankParent {
static int a = 2;
static {
a = 20;
System.out.println("Parent static code");
}
public StaticBlankParent() {
System.out.println("Parent constructor");
System.out.println("Parent var a=" + a);
}
}
1.总是可以“父=子”赋值。此时不需要类型转换。
2.可以执行类型转换“子=(子)父”,但需要运行时进行检查。如果父类变量引用的是正确的子类型,赋值将执行。如果父类变量引用的是不相关的子类型,将会生成class castException异常。
即:如果父类的实例是在子类的实例上塑造的,“子=(子)父”时就不会抛出异常。
如:
A 是B的父类。
A a= new B(); //父类A的对象a是在子类B的对象上塑造的。
就可以:
B b= (B)a;
3.决不能在不相关的任何类之间执行类的赋值或者类型转换。即类的造型转换仅限于有继承关系的俩个类的对象之间。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值