OCA Java imtahan mövzuları

Instance Initializer Blocks | Order of Initialization

Instance Initializer Blocks

Bəzən kod blokları metodun daxilində olur və metod çağırılanda həmin kod blokları metoddakı kod ardıcıllığına uyğun icra edilir. Bəzən isə bu kod blokları metoddan kənarda olur. Həmin kod blokları instance initializers adlanır.

public class TestCodeBlocks { 
  
    public static void main(String[] args) {
        new TestCodeBlocks(); // bu comment`e salinsa, ancaq step 2 --> step 3 --> step 4
        System.out.println("step 2");
        {System.out.println("step 3");}
        System.out.println("step 4");
    }   

    { System.out.println("step 1"); }
}

Output:

  • step 1
    step 2
    step 3
    step 4

 

Order of Initialization

“Order of initialization” ilə bağlı aşağıdakı qaydalar mövcuddur:

  • Dəyişənlər (fields) və instance initializer bloklar faylda (və ya class`da) mövcud olduğu ardıcıllığa uyğun olaraq icra edilir;
  • Konstruktor, bütün dəyişənlər (all fields) və instance initializer bloklar icra edildikdən sonra (have run) icra olunur.
public class MySweety {

    private String name = "Leila"; // step-1
    { System.out.println(name + " became a mother."); } // step-2

    public MySweety() { 
        System.out.println("My sweety was born."); // step-3
        name = "Aliya"; // step-4
    }

    public static void main(String[] args) {
        MySweety mySweety = new MySweety();
        System.out.println("Her name is " + mySweety.name); // step-5
    } 
}

Output:

  • Leila became a mother.
    My sweety was born.
    Her name is Aliya

 

Bütün mövzulara bax

About the author

Mushfiq Mammadov

1 Comment

Faraculla üçün bir cavab yazın X


The reCAPTCHA verification period has expired. Please reload the page.

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.