How to call a static block in one class from another class?. And is it possible to call a free floating block in one class from another class?. How?

Questions by gothlururaaja

Showing Answers 1 - 16 of 16 Answers

alen strange

  • Jan 28th, 2007
 

If the scope allows we can call static class members by ClassName.MemberName, because static member are fields of class instead of objects.

  Was this answer useful?  Yes

Vibs

  • May 18th, 2007
 

A static block of one class wll be called by another class when we try to instantiated the first class(the one having static block).
for e.g.

public class Test

{

int i ;static Test tobj = null;

 

public Test ()

{

 

System.out.println("Constructor");

}

static

{

System.out.println("static");

}

 

}

public final class SubTest {

 

 

 

public SubTest()

{}

public static void main(String a[])

{

Test t = new Test();//Static block of Test class will be called here

}

 

}

NavaNani

  • Apr 6th, 2008
 

Non static blocks & Static blocks are executed one by one by the order of their defintion before any constructor is being executed.

Static blocks can also be invoked without creating instance of the Class(without actually calling constructors) by simply loading the Class.

Class.forName("ClassThatContainsStaticBlock");

static block gets executed whenever is class is loaded by the JVM
so what you can do is.....

write is class having static block in it ---> compile it  --> write another class (ensure that first class is accessible to the second class) and instattiate first class in it ----> your static block will get executed



vinny

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions