package com.practice;
public class BlockThisDemo {
public static int a = 6;
{
a = 10;
System.out.println("2、非静态代码块执行a=" + a);
}
static {
a = 6;
System.out.println("1、静态代码块执行a=" + a);
}
public BlockThisDemo() {
this(a);
System.out.println("5、"+a);
System.out.println("6、无参构造方法执行a=" + a);
}
public BlockThisDemo(int a) {
System.out.println("3、"+a);
System.out.println("4、"+this.a);//
}
public static void main(String[] args) {
System.out.println("main");
BlockThisDemo tsc = new BlockThisDemo();
}
}
先执行静态代码块输出6
在执行main函数输出main
先执行this(a)这里a为6
在执行代码块输出10
执行有参构造函数输出6和10,因为6是this(a)这里的a,所以为6,this.a就是静态变量a是10
在执行无参构造函数输出10,10
你用debug模式,一步一步的看就知道为什么输出10。请采纳,谢谢
被static修饰的变量或者方法是属于类本身,而不属于类的实例。在类被加载进虚拟机的时候就已经初始化了,所以默认a的值是6,只有调用了this时a的值才会是10,而2、非静态代码块执行a=10这个是因为局部变量给覆盖了