21 Eylül 2016 Çarşamba

Static Constructor - Static Block

1. Static Block
Static Constructor aynı zamanda "Static Initialization Block", "Static Initializer" olarak ta bilinir.

Tanımlama
Şöyle yaparız.
public class Foo {
  static {
    System.out.println("Foo class loaded!");
  }
  ...
}
Ne Zaman Çalışır
Açıklaması şöyle
Class Loading and initialization are 2 different things. A class can be loaded but not initialized until it is really necessary. Static initializers are run only when a class is being initialized <> NOT loaded, "initialized"
Şu satır çalıştırmaz, çünkü sadece loading yapar.
Class<Foo> c = Foo.class;
Çalışması için şöyle yaparız.
Class<?> c = Class.forName ("Foo");
Çalışması için şöyle yaparız.
Foo f = new Foo ();
Static Block, Static Üye Alan'dan Sonra Çalıştırılabilir
Örnek
Şöyle yaparız
public class Helper {
  public static final Bicycle bicycle = new Bicycle("blue", 5L);
  static {
    bicycle.setTag("mountain");
  }
}
2. Instance Blocks
Şöyle yaparız
private LocalDate todayDate ;
{
    todayDate = LocalDate.now();
}
3. Order of Initialization
Açıklaması şöyle
So when there is a child class and we call the constructor of the child class following order will be followed:

1. Static Blocks of Super class and Child class will be loaded
2. Instance block of the Super class loads
3. Constructor of the Super class loads
4. Instance block of the Child class loads
5. Constructor of the Child class loads
Örnek
Elimizde şöyle bir kod olsun
class Foo {
  static { System.out.print("Static 1, "); }

  { System.out.print("Instance 1, "); }

  public Foo() {
    System.out.print("Foo Constructor, ");
  }
  
}

class Bar extends Foo {
  static { System.out.print("Static 2, "); }

  { System.out.print("Instance 2, "); }

  public Bar() {
    System.out.print("Bar Constructor, ");
  }
 
}

Bar bar = new Bar();
Çıktısı şöyle. Yani önce ata sınıfın static, daha sonra kalıtan sınıfın static metodları çalışıyor.
Daha sonra her sınıfın instance + constructor metodları kalıtıma göre çalıştırılıyor
Output:
Static 1, Static 2, Instance 1, Foo Constructor, Instance 2, Bar Constructor



Hiç yorum yok:

Yorum Gönder