Java中,类的加载顺序

class Person{
  public Person(int n){System.out.println(String.format("new Person(%s)",x));}
}
public class PersonTest(){
  Person p1=new Person(1);
  static Person p2=new Person(2);
  
  static{
    System.out.println("static code block");
  }


  {
    System.out.println("no-static code block");
  }


  public PersonTest(){
    System.out.println("new PersonTest()");
  }


  static Person p3=new Person(3);
  Person p4=new Person(4);
  
  public static void main(String[] args){
    //
    new PersonTest();
    System.out.println("*************");
    new PersonTest();
    
  }
}


/** output
new Person(2)
static code block
new Person(3)
new Person(1)
non-static code block
new Person(4)
new PersonTest()
*************
new Person(1)
non-static code block
new Person(4)
new PersonTest()
**/


如果main方法中,什么都不做.只是调用static main()方法.
/** output
new Person(2)
static code block
new Person(3)
**/


从上面看出来,在不考虑继承的条件下,类中属性和构造函数的加载顺序如下:
(1)static 属性 / static 代码块         注意:有多个static属性和static代码块时,按声明顺序加载


(2)non-static 属性/ non-static 代码块  注意:有多个non-static属性和non-static代码块时,按声明顺序加载


(3)constructor构造函数
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值