Static Constructors VS Non-Static Constructors

วรวลัญช์ เปลี่ยนสี 650710581

ทบทวนความรู้เกี่ยวกับ Constructor

Constructor (คอนสทรักเตอร์) คือเมธอดที่มีชื่อเดียวกับคลาสและไม่มีการกำหนดชนิดของข้อมูลที่ถูกส่งกลับ (return type) เช่น ถ้าเราสร้างคลาส ชื่อ Dog ส่งผลให้ Constructor ของคลาส Dog ชื่อว่า Dog() เป็นเมธอดพิเศษที่ทำงานโดยอัตโนมัติทันที เมื่อมีการสร้าง Instance (ออบเจ็กต์ที่ถูกสร้างจากคลาส) หรือสร้างออบเจ็กต์ขึ้นมาด้วยคำสั่ง new และนำออบเจ็กต์ดังกล่าวไปใช้งานในลำดับถัดไป โดยที่ภาษา C# รองรับ constructor 2 แบบด้วยกัน คือ 1. class constructor (static constructor) และ 2. instance constructor (non-static constructor)

ทำความรู้จักกับ Static Constructor

Static Constructor ใช้ในการกำหนดค่าเริ่มต้นให้กับข้อมูลที่เป็นแบบคงที่ ที่มีการจองพื้นที่ในหน่วยความจำตั้งแต่โปรแกรมเริ่มทำงาน จะไม่มีการรับพารามิเตอร์ ทันทีที่มีการอ้างอิงถึงคลาสครั้งแรกจะถูกเรียกโดยอัตโนมัติ ก่อนที่จะมีการสร้าง Instance ครั้งแรกของคลาสหรือก่อนที่จะมีการเรียกใช้ static members ใดๆ โดย Static Constructor จะถูกเรียกใช้แค่ครั้งเดียวสำหรับคลาสนั้น ๆ

ตัวอย่างโค้ดในภาษา C#

C#
class SimpleClass
{
    // Static variable that must be initialized at run time.
    static readonly long baseline;

    // Static constructor is called at most one time, before any
    // instance constructor is invoked or member is accessed.
    static SimpleClass()
    {
        baseline = DateTime.Now.Ticks;
    }
}

จากโค้ดตัวอย่าง เป็นการกำหนดค่าเริ่มต้นให้กับตัวแปร static คือ baseline ในคลาส SimpleClass โดยจะถูกเรียกอัตโนมัติ 1 ครั้งก่อนที่มีการสร้างอินสแตนซ์ของคลาสหรือก่อนที่สมาชิกใด ๆ จะถูกเรียกใช้ ในส่วนของ baseline; จะกำหนดค่าได้เพียงครั้งเดียวในช่วงรันโปรแกรม เพราะมีลักษณะเป็น readonly

ในภาษาอื่นๆ เช่น Java , C , Python มีการจัดการเกี่ยวกับ Static Constructor ที่ต่างกันไป

  • Java : ไม่สามารถประกาศ constructor เป็น static ได้ เพราะในภาษา Java constructor มีหน้าที่ในการสร้างอ็อบเจ็กต์ของคลาส แต่สามารถใช้ static block ในการกำหนดค่าตัวแปร static ของคลาสแทนได้

public class StaticInitializationExample {  
    private static String message;  
    static {  
        // Static initialization block  
        message = "Hello, World!";  
    }  
    public static void main(String[] args) {  
        // Accessing the static variable  
        System.out.println(message);  
    }  
}
  • C : ไม่มีแนวคิด static constructor โดยตรงแต่สามารถใช้ Function กำหนดค่าได้

  • Python : ไม่มีแนวคิด static constructor โดยตรงแต่สามารถใช้ Function กำหนดค่าได้

ทำความรู้จักกับ Non-Static Constructor

Non-Static Constructor ใช้สำหรับกำหนดค่าเริ่มต้นให้กับสมาชิกที่ไม่ใช่ static ของคลาส มีชื่อเดียวกับคลาสและสามารถรับพารามิเตอร์ได้ จะถูกเรียกใช้เมื่อมีการสร้าง instance ของคลาสโดยใช้คีย์เวิร์ด new และยังสามารถกำหนด Access Modifiers เช่น public หรือ private เพื่อควบคุมการเข้าถึง constructor ได้

ตัวอย่างโค้ดในภาษา C#

class MyClass {  
     // Instance variable to be initialized in the non-static constructor  
     private int instanceVariable;  
     public MyClass(int value)  {  
      Console.WriteLine("Non-static constructor is called.");  
      instanceVariable = value;  
   }  
    public void PrintInstanceVariable()  {  
    Console.WriteLine($"Instance variable value: {instanceVariable}");  
   }  
}  
class Program  {  
    static void Main()  {  
          MyClass myObject = new MyClass(10);  
          myObject.PrintInstanceVariable();  
          MyClass anotherObject = new MyClass(20);  
          anotherObject.PrintInstanceVariable();  
    }  
}

จากโค้ดตัวอย่าง มีตัวแปร instance ที่ชื่อ instanceVariable ถูกกำหนดค่าใน non-static constructor คือ MyClass(int value) โดยจะพิมพ์ข้อความเมื่อมีการเรียกใช้ constructor นี้ มีการรับ parameter ชื่อ value ในส่วนของคลาส Main() มีการสร้าง instance 2 ตัว โดยกำหนดค่าให้ตัวแปรinstanceVariable ของแต่ละ instance เป็น 10 และ 20 และเรียกเมธอด PrintInstanceVariable() เพื่อพิมพ์ค่าของตัวแปรนั้น

ในภาษาอื่นๆ เช่น Java , C , Python มีการจัดการเกี่ยวกับ Non-Static Constructor ที่ต่างกันไป

  • Java : เรียกว่า Instance Constructor จะถูกเรียกใช้ทุกครั้งที่มีการสร้างออบเจ็กต์ใหม่ของคลาส

// Default Constructor
import java.io.*;

class GFG {

    // Default Constructor
    GFG() { System.out.println("Default constructor"); }

    // Driver function
    public static void main(String[] args)
    {
        GFG hello = new GFG();
    }
}
  • C : ไม่มีแนวคิดของ Non-Static Constructor เพราะเป็นภาษาโปรแกรมเชิงกระบวนการ (Procedural Programming) แต่สามารถใช้ struct ในการกำหนดค่าเริ่มต้นให้ข้อมูลหรือฟิลด์ที่ถูกกำหนดอยู่ภายใน struct ได้

  • Python : เรียกว่า __init__() ใช้กำหนดค่าเริ่มต้นให้กับสมาชิกของคลาสที่เป็น non-static จะถูกเรียกใช้ทุกครั้งที่มีการสร้างออบเจ็กต์ใหม่ของคลาส

class GeekforGeeks:

    # default constructor
    def __init__(self):
        self.geek = "GeekforGeeks"

    # a method for printing data members
    def print_Geek(self):
        print(self.geek)


# creating object of the class
obj = GeekforGeeks()

# calling the instance method using the object obj
obj.print_Geek()

ความแตกต่างระหว่าง Static Constructors กับ Non-Static Constructors

Topic
Static Constructor
Non-Static Constructor

การประกาศ (Declaration)

ใช้ keyword "static" เพื่อสร้าง static constructor มีการใช้ Static modifier เพื่อประกาศสมาชิกของคลาส

ไม่ต้องใช้ keyword อะไรเลยในการสร้าง non-static constructor มีการใช้ Instance ในการ executed

การเรียกใช้ (Calling)

ถูกเรียกแบบโดยนัย (implicitly) จะเรียกอัตโนมัติเมื่อคลาสโหลดครั้งแรกโดย run time

ถูกเรียกแบบชัดเจน (explicitly) จะเรียกในขณะสร้างอ็อบเจ็กต์ โดยใช้คำว่า new

การดำเนินการ (Execution)

จะ execution อัตโนมัติทันทีหลังจากคลาสถูก initialized

จะ execution หลังจากสร้าง instance ของคลาส

เวลาของการดำเนินการ (Times of Execution)

จะ execute ครั้งเดียว

ถ้าไม่มีการสร้าง instance เวลาการดำเนินการจะเป็น 0 แต่ถ้ามีการสร้าง instance n จำนวนจะมีเวลาการดำเนินการ n ครั้ง

การกำหนดค่าเริ่มต้นให้กับตัวแปร (Initialization of fields)

ใช้เพื่อกำหนดค่าเริ่มต้นให้ static fields/ static variables

ใช้เพื่อกำหนดค่าเริ่มต้นให้ non-static fields /static variables หรือ non-static variables

Parameters

ไม่สามารถรับ parameters ได้

สามารถรับ parameters ได้

Overloading

ไม่สามารถ overloaded ได้

สามารถ overloaded ได้ ทำให้มี constructor หลายตัวที่มีพารามิเตอร์ต่างกันได้

ตัวระบุการเข้าถึง (Access Specifier)

ไม่มี access specifier

มี access specifier

การทำ Late Binding

ไม่สามารถทำ late binding ได้

สามารถทำ late binding ได้ผ่าน polymorphism ในคลาสที่สืบทอดกัน

ตัวอย่างโค้ดภาษา C# เพิ่มเติม

using System; 
  
class Geeks{ 
  
// Declaration of 
// static constructor 
static Geeks() 
{ 
    Console.WriteLine("Static constructor"); 
} 
  
// Declaration of 
// non-static constructor 
public Geeks() 
{ 
    Console.WriteLine("Non-Static constructor"); 
} 
  
// Main Method 
static void Main(string[] args) 
{ 
  
    Geeks obj1 = new Geeks(); 
    Geeks obj2 = new Geeks(); 
} 
}

จากโค้ดตัวอย่าง เป็นการใช้ constructor ทั้งแบบ static constructor และ non-static constructor ในคลาส Geeks ซึ่ง static constructor จะถูกเรียกใช้โดยอัตโนมัติเมื่อคลาสถูกเรียกใช้งานครั้งแรก ไม่จำเป็นต้องสร้างอ็อบเจกต์ ส่วน non-static constructor จะถูกเรียกใช้งานเมื่อมีการสร้างอ็อบเจกต์ ซึ่งในโค้ดตัวอย่างมีการสร้างอ็อบเจกต์ 2 ตัวคือ obj1 และ obj2 ทำให้ได้ output ที่มาจาก static constructor 1 ครั้ง และ non-static constructor 2 ครั้ง

Reference

บทความทบทวนเกี่ยวกับ Constructor :

ศุภชัย สมพานิช. (2566). คู่มือ Coding และพัฒนาแอปพลิเคชันด้วย C#. หน้า 196.

Chandrakant Upadhyay. (2566). Static Constructor In C# And Its Usages. สิบค้น. 5 ตุลาคม 2567, จาก https://www.c-sharpcorner.com/article/static-constructor-in-C-Sharp-and-their-usages/

บทความทำความรู้จักกับ Static Constructor :

Chandrakant Upadhyay. (2566). Static Constructor In C# And Its Usages. สิบค้น. 5 ตุลาคม 2567, จาก https://www.c-sharpcorner.com/article/static-constructor-in-C-Sharp-and-their-usages/

microsoft. (2567). Static Constructors (C# Programming Guide). สืบค้น. 5 ตุลาคม 2567, จาก https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors

ตัวอย่างโค้ด Static Constructor ในภาษา C# :

microsoft. (2567). Static Constructors (C# Programming Guide). สืบค้น. 5 ตุลาคม 2567, จาก https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors

ตัวอย่างโค้ด Static Constructor ในภาษา Java :

Can Constructor be Static in Java?. (n.d). สืบค้น. 5 ตุลาคม 2567, จาก https://www.javatpoint.com/can-constructor-be-static-in-java#

บทความทำความรู้จักกับ Non-Static Constructor :

Difference between Static Constructors and Non-Static Constructors in C#. (n.d). สืบค้น. 5 ตุลาคม 2567, จากhttps://www.javatpoint.com/difference-between-static-constructors-and-non-static-constructors-in-c-sharp

ตัวอย่างโค้ด Non-Static Constructor ในภาษา C# :

Difference between Static Constructors and Non-Static Constructors in C#. (n.d). สืบค้น. 5 ตุลาคม 2567, จากhttps://www.javatpoint.com/difference-between-static-constructors-and-non-static-constructors-in-c-sharp

ตัวอย่างโค้ด Non-Static Constructor ในภาษา Java :

Nitsdheerendra. (2567). Java Constructors. สืบค้น. 5 ตุลาคม 2567, จาก https://www.geeksforgeeks.org/constructors-in-java/

ตัวอย่างโค้ด Non-Static Constructor ในภาษา Python :

vivekkothari. (2567). Constructors in Python. สืบค้น. 5 ตุลาคม 2567, จาก https://www.geeksforgeeks.org/constructors-in-python/

ความแตกต่างระหว่าง Static Constructor และ Non-Static Constructor :

anshul_aggarwal. (2565). C# | Difference between Static Constructors and Non-Static Constructors. สืบค้น. 5 ตุลาคม 2567, จาก https://www.geeksforgeeks.org/c-sharp-difference-between-static-constructors-and-non-static-constructors/

Isha Malhotra. (2561). Difference Between Static Constructor and Non-Static Constructor. สืบค้น. 5 ตุลาคม 2567, จาก https://tutorial.techaltum.com/difference-between-static-and-non-static-constructor.html

Pranaya Rout. (2565). Static vs Non-Static Constructors in C#. สืบค้น. 5 ตุลาคม 2567, จาก https://dotnettutorials.net/lesson/static-vs-non-static-constructors-in-csharp/

ตัวอย่างโค้ด Static Constructor และ Non-Static Constructor เพิ่มเติมในภาษา C#:

anshul_aggarwal. (2565). C# | Difference between Static Constructors and Non-Static Constructors. สืบค้น. 5 ตุลาคม 2567, จาก https://www.geeksforgeeks.org/c-sharp-difference-between-static-constructors-and-non-static-constructors/

Presentation

VDO Clip

Last updated