Reputation: 105
class A
{
static{
get();
}
static void get(){
System.out.println("HELLO");
}
}
class B extends A
{
public static void main(String[] args) {
}
}
Output:
HELLO
How is static method of class A
getting called. I can understand static method of B
getting called but not of A
.
Upvotes: 0
Views: 99
Reputation: 36304
During compilation the compiler knows that B is dependant on A. It passes the same data to the JVM. During loading phase of class B, the JVM reads metadata sent by the compiler and finds out that B
is dependant on A
and hence loads (and runs static initializers) of A
then continues to load B
and then initializes B
.
If we had 2 classes Sample
and Test extends Sample
the Class Constant Pool (part of byte code ) for Test
would have :
Constant pool:
#1 = Class #2 // Test
#2 = Utf8 Test
#3 = Class #4 // Sample <---- reference
#4 = Utf8 Sample
#5 = Utf8 <init>
#6 = Utf8 ()V
#7 = Utf8 Code
#8 = Methodref #3.#9 // Sample."<init>":()V <-- init Sample
#9 = NameAndType #5:#6 // "<init>":()V
#10 = Utf8 LineNumberTable
#11 = Utf8 LocalVariableTable
#12 = Utf8 this
#13 = Utf8 LTest;
#14 = Utf8 main
#15 = Utf8 ([Ljava/lang/String;)V
#16 = Utf8 args
#17 = Utf8 [Ljava/lang/String;
#18 = Utf8 SourceFile
#19 = Utf8 Sample.java
If you run java with verbose:class
option then grep it, you will be able to see that the dependant class is being loaded.
java -verbose:class Test | grep 'Sample'
[Loaded Sample from file:/Users/XXXX/Workspaces/SampleTest/Sample/bin/] <== Sample loaded first because test depends on Sample.
[Loaded Test from file:/Users/XXXX/Workspaces/SampleTest/Sample/bin/]
Upvotes: 0
Reputation: 71
All Static blocks are executed at class loading time ... duplicate question When is the static block of a class executed?
Upvotes: 0
Reputation: 201
To execute the main method of class B, class B has to be loaded.
Class B extends class A, so to load B, class A must be loaded.
When class A is loaded, its static initializer is invoked, calling the get() method and printing "HELLO".
Upvotes: 1
Reputation: 2691
In inheritance class loading is happens from top to bottom i.e. Parent to child.
It first loads the parent class in your case A
and then loads the child class in your case B
. And when class loads its static block get called first that why its printing HELLO
Upvotes: 0
Reputation: 285450
Because B extends from A, if the B class is loaded, then the A class has to get loaded, and if it is loaded, its static initializer block must be called.
Upvotes: 3
Reputation: 4668
Because, since B
is inheriting A
, B
has to load A
when main()
executes. This activates the get()
function since it is in the static block.
Upvotes: 1