java 中执行顺序

加载时:

1.先加载父类,再加载子类

2.按static 修饰的模块或属性的顺序进行加载

3.属性如果为类对象,则非空有值时才会初始化,加载属性对象所对应的类,并实例化

4.main方法(也是static)修饰的最后执行


实例化:

1.先实例化父类,再实例化子类

2.属性如果为对象,即没有使用static修饰时,则非空有值时才会初始化,加载属性对象所对应的类,并实例化

例子如下:

public class Test {
    static Person person= new Person("Test");
    static{
        System.out.println("test static");
    }
     
    public Test() {
        System.out.println("test constructor");
        person=new Person("Test constructor");
    }
     
    public static void main(String[] args) {
        System.out.println("============onload completed");
        new MyClass();
    }
}
 
class Person{
    static{
        System.out.println("person static");
    }
    public Person(String str) {
        System.out.println("person "+str);
    }
}
 
 
class MyClass extends Test {
    Person person = new Person("MyClass");
    static{
        System.out.println("myclass static");
    }
     
    public MyClass() {
        System.out.println("myclass constructor");
    }
}


结果:

person static
person Test
test static
============onload completed
myclass static
test constructor
person Test constructor
person MyClass
myclass constructor





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值