Static In Java
static is a really common keyword that is heavily used in java programming.
1.why do we need to use static in java?
1). The most important reason for using static keyword heavily in java is to efficiently manage the memory.
Generally, if you want to access methods or variables inside a class, you need to create an instance or object of the class firstly.
However, if you want to just access only certain methods or other members of the class and you don’t want to create an new instance. This is where you should use static keyword.
2). Using static for some properties that are common in some objects, they can share the some properties and save memory.
For example, students who study at the same school, they share the same school name.
*Static Variables
static variables are global variables, which means they can be shared among all objects in the class level and without referencing their class name.
public class StaticVariable{
static int a = 1;
public static final int COUNT = 1000;
public static void main(String[] args){
System.out.println(a);
System.out.println(COUNT);
}
}
*Static Block
Static blocks are executed in order and once, when the class is first loaded.
public class Blocks{
static int a = 10;
static int b;
static {
System.out.println("first static block");
b = a;
}
static {
System.out.println("second static block");
}
public static void main(String[] args){
System.out.println(a);
System.out.println(b);
}
}
*Static Method
static method can access only static data, static method can be executed by just referencing their names.
public class StaticMethod{
public static int COUNT = 1;
public void NonStatic(){
int NONSTATIC = 2000;
System.out.println("nonstatic attribute" + NONSTATIC);
}
public static void Count(){
System.out.println("static attribute" + COUNT);
}
public static void main(){
Count();
StaticMethod s = new StaticMethod();
s.NonStatic();
}
}
*Static Nested Class
Nested class is a type of class that was defined in a class.
(1) an instance of a nested class cannot be used without creating an instance of outer class
class Person{
private AGE = 66;
public class Female{
private static String name = "Amanda";
public void printName{
System.out.println(name);
}
}
}
class Test{
public static void main(String[] args){
Person p = new Person();
Person.Female pf = new Person.Female();
pf.printName();
}
}
(2) an instance of a nested static class can be used by just referencing outer class name.
class OuterClass{
private int NUMBER = 100;
private static String message = "This is an outer static string";
public static class NestedStaticClass{
public void printMessage{
System.out.println(message);
}
}
}
class Test{
public static void main(String[] args){
OuterClass.NestedStaticClass on = new OuterClass.NestedStaticClass();
on.printMessage();
}
}
(3) inner static class can access only static members in outer class, however inner non-static class can access all of members of outer class.