2

assuming the following example:

public abstract class A {

  public void readList() {
    for (Integer o : InnerA.INT_LIST) {
      System.out.println(o);
    }
  }

  public static class InnerA {

    protected static List<Integer> INT_LIST;

    static {
      INT_LIST = new ArrayList<Integer>();
      INT_LIST.add(1);
    }
  }
}

public class B extends A {      

  public static class InnerB extends InnerA {
    static {
      INT_LIST.add(2);
    }
  }
}

My assumtion was, that when I call

new B().readList();

the output would be

1
2

but instead it is

1

Adding the constructor

public B() {
    new InnerB();
}

leads to the expected behaviour. I thought since the nested class is static, it gets initialized when a new B object is created (it obviously is when A is initialized).

Can someone please explain this to me?

Thanks.

0

1 Answer 1

1

Let's see the implementation of readList() first:

public void readList() {
  for (Integer o : InnerA.INT_LIST) {
    System.out.println(o);
  }
}

It is obviously that it print all elements in the InnerA.
Class B extends Class A and doesn't override readList() function. So the behavior of new B().readList() is print all elemtns in the InnerA, too.

Since the InnerA.INT_LIST only has a elements added in static block of InnerA, it only has 1 elements.

Actually, your code never use class InnerB. JVM do not load it so its static block is not executed.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes correct, class B never loads because of lazy loading. So, the static initializer never executes.
Ok, did not know about this lazy loading. So I either override readList() or add the new InnerB() in the constructor of B. Thanks EDIT overriding readList() and iterating through InnerB.INT_LIST does not work either. The only thing that works is calling new InnerB() in the constructor of B.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.