I'm trying to understand why the JVM decides to load certain classes when it doesn't appear it needs to. Consider the following example code:
public class Foo {
public void foo() {
}
static class Bar {
}
public Bar bar() {
return new Bar();
}
}
When calling new Foo().foo()
, Bar
is not loaded by the classloader since it's not needed. But, if we change the example to have bar
return an instance of a sub-class:
public class Foo {
public void foo() {
}
static class Bar {
}
static class BigBar extends Bar {
}
public Bar bar() {
return new BigBar();
}
}
Calling new Foo().foo()
causes the classloader to load both the Bar
and BigBar
classes even though neither of them are needed. Why?
Aside from this specific scenario, is there a way to learn why the JVM decides it needs to load a class, in general?