[Java] Static

Back-End/Java_1 2016. 5. 11. 15:16
donaricano-btn

Static

a static member is a member of a class that isn't associated with an instance of a class. Instead, the member belongs to the class itself. As a result, you can access the static member without first creating a class instance


1. Example for static variable and methods

1_1. static variable

Static variables are belongs to the class and not to the object


1_2. static method

Static methods are also similar to static variable


1_3. Example


2. Example for static block

Static blocks are nothing but a normal block of code, enclosed in braces {}, preceded with static keyword.

These static blocks will be called when JVM loads the class into memory. Incase a class has multiple static blocks across the class, then JVM combines all these blocks as a single block of code and executes it


2_1. Example


3. Example for static block vs constructor

Java static blocks will be called when JVM loads the class into memory, means it will be called only once. But constructor will be called everytime when you create an object. 


3_1 Example


4. Example for Singleton class using static block

Since static block will be called only once, we can use static block to develop singleton class.

To create singleton class, make constructor as private, so that you cannot create object outside of the class. Create a private static variable of same class type, so that created object will be pointed to this reference. Now create static block, and create object inside static block. Since static block will be called only once, the object will be created only once.


4_1. Example


5. STATIC import

 We can access any static fields or methods with reference to the class name. Static imports allow us to import all static fields and methods into a class and you can access them without class name reference

5_1. Source






'Back-End > Java_1' 카테고리의 다른 글

[Java] JDK, JRE, and JVM  (0) 2016.06.03
[Java] Exception  (0) 2016.05.18
[Java] Constructor  (0) 2016.05.17
[Java] Enum  (0) 2016.05.13
[Java] Array  (0) 2016.05.12
블로그 이미지

리딩리드

,