本文收集平时看到的各种有趣的面试题。
--------------------------------------------------
父类,子类初始化顺序问题。
- public class Test6 {
- public static int i = Test7.j;
- {
- i++;
- }
- static {
- i = 10;
- }
- public Test6() {
- i++;
- }
- }
- public class Test7 extends Test6 {
- public static int j = Test6.i;
- static {
- j++;
- }
- {
- j++;
- }
- }
- public class Main {
- public static void main(String[] args) {
- Test7 t7 = new Test7();
- System.out.println("字段I的值是【" + Test6.i + "】");
- System.out.println("字段J的值是【" + Test7.j + "】");
- }
- }
- public class Main2 {
- public static void main(String[] args) {
- Test6 t6 = new Test6();
- System.out.println("字段I的值是【" + Test6.i + "】");
- System.out.println("字段J的值是【" + Test7.j + "】");
- }
- }
- public class DispatchTest {
- public static void main(String[] args) {
- Base b = new Sub();
- System.out.println(b.x);
- }
- }
- class Base {
- int x = 10;
- public Base() {
- this.printMessage();
- x = 20;
- }
- public void printMessage() {
- System.out.println("Base.x = " + x);
- }
- }
- class Sub extends Base {
- int x = 30;
- public Sub() {
- this.printMessage();
- x = 40;
- }
- public void printMessage() {
- System.out.println("Sub.x = " + x);
- }
- }