- Java code
public class Sub extends Super { int argA; static int argB; int argC = 13; { System.out.println("动态语句块:Sub.argA = " + (argA = 11)); } static{ System.out.println("静态语句块:Sub.argB = " + (argB = 12)); } Sub(){ //super(); System.out.println("构造方法块:Sub.argC = " + argC); print(); print(argB); argA = 30; } void print(int argA) { System.out.println("sub.print(args)"); System.out.println(argA); } void print(){ System.out.println("sub.print()"); System.out.println(argA); System.out.println(argB); } public static void main(String[] args) { System.out.print(new Sub().argA); }}class Super { protected int argA = 21; protected static int argB; static{ argB = 22; } Super() { print(); print(argA); argA = 23; } void print(int argA) { System.out.println("super.print(args)"); System.out.println(argA); } void print() { System.out.println("super.print()"); System.out.println(argA); System.out.println(argB); }}
执行过程是这样的吗?
static int argB;
int argA;
int argC;
static{
System.out.println("静态语句块:Sub.argB = " + (argB = 12));
}
Sub(){
super();
argC = 13;
System.out.println("动态语句块:Sub.argA = " + (argA = 11));
System.out.println("构造方法块:Sub.argC = " + argC);
print();
print(argB);
argA = 30;
}
求解释。
------解决方案--------------------
顺序+覆盖的问题
------解决方案--------------------
- Java code
public class Sub extends Super { int argA; static int argB; int argC = 13; { //这里应该是在new 一个Sub实例的时候才打印 System.out.println("动态语句块:Sub.argA = " + (argA = 11)); } static{ System.out.println("------------Sub()静态数据模块.-----------") ; System.out.println("静态语句块:Sub.argB = " + (argB = 12)); } Sub(){ //super(); System.out.println("构造方法块:Sub.argC = " + argC); print(); print(argB); argA = 30; } void print(int argA) { System.out.println("sub.print(args)"); System.out.println(argA); } void print(){ System.out.println("sub.print()"); System.out.println(argA); System.out.println(argB); } public static void main(String[] args) { System.out.print(new Sub().argA); }}class Super { protected int argA = 21; protected static int argB; static{ System.out.println("------------Supper()静态数据模块.-----------") ; argB = 22; } Super() { System.out.println("------------Supper()构造函数 begin.-----------") ; print(); print(argA); argA = 23; System.out.println("------------Supper()构造函数 end.-----------") ; } void print(int argA) { System.out.println("super.print(args)"); System.out.println(argA); } void print() { System.out.println("------------Supper().print() begin .-----------") ; System.out.println("Supper().argA = " + argA); System.out.println("Supper().argA = " + argB); System.out.println("------------Supper().print() end .-----------") ; }}
------解决方案--------------------