Link to home
Start Free TrialLog in
Avatar of Squadless
Squadless

asked on

Static block java

I wrote up this little scenario.  What would be the sequence of the methods called.  

I think the order will be:
1) static block,
2) the constructor
3) constructor of Blah.

The 3rd is trivial, but are 1 and 2 in correct order?  - This is granted that another class would call the "method" function of TestClass.

Thanks.
public class TestClass extends Blah{

TestClass(){
  super();
}

public void method(){
 TestClass baa = new TestClass();
}

static blockOfCode{

}

Open in new window

Avatar of for_yan
for_yan
Flag of United States of America image

I think this is correct.
I think static block will be executed when this class will be loaded.

But then for some third party object ro call the method() it will first need to
create instance of TestClass - then it would first have to call the constructor.

You probably meant to  make the method() static method ?
static block will be excuted when the class is loaded

But constructor will only be executed when someone creates instance or calls method.

And the superclass constructor will be called from executing constructor as written
Avatar of Squadless
Squadless

ASKER

Lets take 2 scenarios.  
One - method is NOT static and when a 3rd party object does create a instance of test class then calls instanceVar.method();
Two - method IS static when a 3rd party object invokes TestClass.method();

How would that differ?  If method is static, when calling TestClass.method(), we are directly going to the static method class... yes right , we're not creating a instance of TestClass so the static block is not yet executed.  So IF and only IF we create a regular instance of a class, static blocks execute first.  

So What if i had
final int value = 7; above the constructor
final int valueB = 8; INSIDE the constructor
final int valueC = 9; INSIDE the function "method".

Would any of the finals initialize before the static block?
Avatar of Mick Barry
>  So IF and only IF we create a regular instance of a class, static blocks execute first.  

No the static block will be called first in both scenarios (assuming the class has not already been loaded)

> Would any of the finals initialize before the static block?

no
SOLUTION
Avatar of for_yan
for_yan
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial