+ 3
What is the difference between static method and static block in JAVA?Can we declare more than one static block for a Program?
Static method and Static block
2 Réponses
+ 3
Yes you can have more than one static block.
They will run in order. (top-down).
A static block is a block of code that runs ONCE, when the class is loaded.
Example/
class Program{
static {
System.out.println("Load success!");
// The static block
int a = 15;
// can do whatever, but everything is static
}
}
A static method is, well, a method that is static. 😜
(You can review what a method is in the course).
static makes the member bound to the class itself.
So, a static method is a method that is bound to the class rather than an instance of the class.
In order to understand this, you will need some OOP experience.
The following things are results of making something bound to the class:
* It can no longer be Overrided
* It can be accessed through the class
* Is not part of an object instance
Example/
class Program{
static void myMethod(){
// a static method
}
}
+ 4
thanxx for the answer