Static block, Non-static(instance) block, state, behaviour

 There are two types of blocks static and non-static blocks. Static block runs first. But when we create an object of class first runs static block and then non-static block and after constructor of particular class.

package Main;

public class Calculator {

public static int a;
public int b;
static {
System.out.println("static block loaded");
sum(1, 2);
a++;
}

{
System.out.println("non static block loaded");
b++;
a++;
foo();
sum(1, 2);
}

public Calculator() {
System.out.println("Constructor of a class");
}

public static double sum(double a, double b){
return a + b;
}

public void foo(){
System.out.println("salam");
}
}
So we can load a class by typing:
Class.forName("Main.Calculator"); inside we have to mention package name and class name.
package Main;

public class Main {

public static void main(String[] args) throws Exception {
Class.forName("Main.Calculator");
}
}
By doing so we only load static block of this class, and this class being kind of at
start and being deployed.
When we create objects of this class the static block will be executed only once, however
non-static block as much as the count of the object we created.
Static block can only call static methods and variables, whereas non-static block
can call both static and non-static methods and variables.

*State - variables inside class are called state.
*Behaviour - methods inside class are called behaviour.
*Overrride - means use one method head but difference parameters(and body).
package Main;

public class Calculator {

public static int sum(int a, int b){
return a + b;
}

public static double sum(double a, double b){
return a + b;
}
}

Комментарии

Популярные сообщения из этого блога

Lesson1: JDK, JVM, JRE

SE_21_Lesson_11: Inheritance, Polymorphism

SE_21_Lesson_9: Initialization Blocks, Wrapper types, String class