(非)静态代码块,构造函数,变量相关初始化顺序

public class Student {


<span style="white-space:pre">	</span>static{
<span style="white-space:pre">		</span>System.out.println("this is static block ");
<span style="white-space:pre">	</span>}
<span style="white-space:pre">	</span>
<span style="white-space:pre">	</span>{
<span style="white-space:pre">		</span>System.out.println("this is non-static block 1");
<span style="white-space:pre">	</span>}
<span style="white-space:pre">	</span>public Student(int id){
<span style="white-space:pre">		</span>System.out.println("student("+id+")");
<span style="white-space:pre">	</span>}
<span style="white-space:pre">	</span>public Student(){
<span style="white-space:pre">		</span>System.out.println("student()");
<span style="white-space:pre">	</span>}
<span style="white-space:pre">	</span>{
<span style="white-space:pre">		</span>System.out.println("this is non-static block 2");
<span style="white-space:pre">	</span>}
<span style="white-space:pre">	</span>
<span style="white-space:pre">	</span>public static void main(String[] args) {
<span style="white-space:pre">		</span>Student s1 = new Student(1);
<span style="white-space:pre">		</span>Student s2 = new Student(2);
<span style="white-space:pre">		</span>Student p = new Student();
<span style="white-space:pre">	</span>}
<span style="white-space:pre">	</span>
}
this is static block 
this is non-static block 1
this is non-static block 2
student(1)
this is non-static block 1
this is non-static block 2
student(2)
this is non-static block 1
this is non-static block 2
student()


我们new了两个对象,可是静态块只执行了一次,而非静态块执行了两个,且都是在调用构造器之前。我们似乎得出了一些结论:静态块是在类的装载时执行的(装入.class文件后),且只执行一次。而非静态块是在调用构造方法之前执行的,每生成一个实例对象,就会调用一次非静态块。



public class Student {  
 
    public Student(int id) {  
        System.out.println("student(" + id + ")");  
    }  
    
    public Student(){
    System.out.println("Student()");
    }
  
    public static void main(String[] args) {  
        BuildStudent buildStudent = new BuildStudent();  
    }  
}  
  
class BuildStudent {  
Student s1 = new Student(1);  
  
    public BuildStudent() {  
        System.out.println("this is buildStudent's block!");  
        Student s2 = new Student(2);  
    }  
    
    Student s3 = new Student();
  
    Student s4 = new Student(3);  
  
}  


student(1)
Student()
student(3)
this is buildStudent's block!
student(2)


不论变量放在哪儿,都会先于任意一个方法的执行前执行,包括构造方法,而构造方法是一个类必须会执行的方法,不需要显示的进行调用。同时,不论变量在哪儿分布,只要在方法外部,就一定先于方法初始化。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值