0
How to invoke non static block from static block???
3 Answers
+ 5
Example:
class Test{
public static void main (String[ ] ar){
Demo obj = new Demo();
}
}
class Demo{
// Non-static
{
System.out.println(
"Inside a non-static block." );
}
// Constructor
public Demo(){
System.out.println(
"Inside a constructor." );
}
}
So based on this, you can have scenario where you can think of initialize values before instantiation. And non-static block is executed every time an object is created.
⢠The instance initializer block is called when instance of the class is created.
⢠The instance initializer block is invoked after the parent class constructor is invoked (i.e. after super() constructor call).
⢠The instance initializer block comes in the order in which they appear.
⢠They can be used to perform operations those are common to constructors.
+ 4
Can You Call Non-Static Method From a Static?
https://dzone.com/articles/can-you-call-non-static-method-from-a-static
The non-static block (initialiser block) is called whenever a new instance is created and it will be called just before the Constructor. So, anything else like calculation/other logic could be given in the non-static block, as a constructor is used for initializing purpose.
It's only initializer block/non-static block, if it is within the class and outside of a method declaration. A block inside of a method is just code that gets executed as part of the method which you can use as to limit scope of some variable(s).
https://beginnersbook.com/2013/04/java-static-class-block-methods-variables/
https://www.javatpoint.com/instance-initializer-block
http://www.thejavageek.com/2013/07/21/initialization-blocks-constructors-and-their-order-of-execution/
0
class Demo
{
static
{
sop("Static Block running...");
new Demo();
}
//Nonstatic Block
{
sop("Non Static Block running..");
}
}
public class TestDemo
{
main()
{
}
}
-I am invoking non static block from static block.
-Without main declaration or instantiation invoking non static block