intTypePromotion=1
zunia.vn Tuyển sinh 2024 dành cho Gen-Z zunia.vn zunia.vn
ADSENSE

Constructors and Destructors

Chia sẻ: Tien Phuoc Online | Ngày: | Loại File: PDF | Số trang:18

103
lượt xem
8
download
 
  Download Vui lòng tải xuống để xem tài liệu đầy đủ

Constructors and destructors perform special functions as members of classes. Constructors are used to initialize objects. Conversely, you can use destructors to delete an object when it is not required. This chapter introduces the concept of constructors and destructors. In addition, the chapter explains how to implement constructors and destructors. The chapter also explains how constructors and destructors help in identifying the life cycle of the object.

Chủ đề:
Lưu

Nội dung Text: Constructors and Destructors

  1. Chapter 6 Constructors and Destructors Constructors and destructors perform special functions as members of classes. Constructors are used to initialize objects. Conversely, you can use destructors to delete an object when it is not required. This chapter introduces the concept of constructors and destructors. In addition, the chapter explains how to implement constructors and destructors. The chapter also explains how constructors and destructors help in identifying the life cycle of the object. Objectives In this chapter, you will learn to: Implement constructors Implement destructors Identify the life cycle of an object
  2. Implementing Constructors A constructor is a special type of method that is invoked when you create a new instance of a class. A constructor is used to initialize the members of the class. The name of a constructor is the same as the name of the class that contains it. A constructor is complementary to a destructor. It is good programming practice to use both constructors and destructors. The Need of Constructors To initialize member variables, a function can be invoked as soon as an object is created. The following program is an example of writing an initialization function: using System; namespace Calc { class Calculator { static int number1, number2, total; public void Intialize() { number1 = 10; number2 = 20; } public void AddNumber() { total = number1 + number2; } public void DisplayNumber() { Console.WriteLine ("The Total is :{0}", total); } public static void Main(string[] args) { Calculator c1 = new Calculator (); c1.Intialize (); c1.AddNumber (); c1.DisplayNumber (); } } } In the preceding example, the c1 object of the Calculator class has to call the Initialize () member function to initialize the data members number1 and number2. However, you need to ensure that the initialize function is invoked. NIIT Constructors and Destructors 6.3
  3. OOPs offers you a solution to overcome the preceding problem related to ensuring for invoking the initialize function. While designing a class, you can include a special member function within the class. This member function is executed whenever an object of the class is created. Such functions are called constructors. Types of Constructors There are two types of constructors, instance constructors and static constructors. Instance Constructors An instance constructor is called whenever an instance of a class is created. These constructors are used to initialize data members of the class. For automatic initialization, the Calculator class can be rewritten by using a constructor. For example, consider the following code: using System; namespace Calc { class Calculator { static int number1, number2, total; // Constructors have same name as the class. Calculator() { number1 = 10; number2 = 20; } public void AddNumber() { total = number1 + number2; } public void DisplayNumber() { Console.WriteLine ("The Total is :{0}", total); } public static void Main(string[] args) { Calculator c1 = new Calculator (); c1.AddNumber (); c1.DisplayNumber (); } } } 6.4 Constructors and Destructors NIIT
  4. In the preceding code notice that there is no return type specified to the Calculator()constructor. This is because constructors do not return values. The variable number1 is assigned with value 10 and number2 is assigned with value 20 when the constructor is invoked by the Common Language Runtime (CLR). If there are no constructors defined for a class, the compiler creates a default constructor. In such a case, the instantiation of an object of this class invokes the default constructor. Static Constructors Static constructors are used to initialize the static variables of a class. These variables are created using the static keyword and they store values that can be shared by all the instances of a class. These constructors have an implicit private access. The constructors will be invoked only once during the execution of a program. The following example illustrates the implementation of the static constructor: public class Class1 { static int number1; int number2; static Class1() { number1 = 10; //OK. Since Number1 is a static variable in class1 number2 = 3; //Error. Since Number2 is a non-static variable in class1 } } Note In actual practice, constructors are used to initialize data members and not for any input or output operations. Note We can have more than one constructor in a class. Chapter 7 discusses this topic in detail. NIIT Constructors and Destructors 6.5
  5. Constructors with Parameters Objects can be initialized using the default constructor with values hard-coded in the program. But there might be a requirement where the variables need to be initialized with user supplied values. To tackle this problem, a constructor can be modified to accept the user supplied values at runtime. The following code illustrates the use of parameters in constructors: using System; namespace Calc { class Calculator { static int number1, number2, total; //Constructor defined with two integer parameters num1 and num2. Calculator(int num1, int num2) { number1 = num1; number2 = num2; } public void AddNumber() { total = number1 + number2; } public void DisplayNumber() { Console.WriteLine("The Total is :{0}", total); } public static void Main(string[] args) { int var1, var2; Console.WriteLine("Enter Value 1 :"); var1=Convert.ToInt16(Console.ReadLine()); Console.WriteLine("Enter Value 2 :"); var2 = Convert.ToInt16(Console.ReadLine()); Calculator C1 = new Calculator(var1,var2); C1.AddNumber(); C1.DisplayNumber(); Console.ReadLine(); } } } In the preceding code, the initialization values are passed to the member variables at the time of creating the object after accepting values from the user. Therefore, the following statement: Calculator C1 = new Calculator(var1,var2); 6.6 Constructors and Destructors NIIT
  6. invokes the constructor function and passes the initialization values supplied by the user at runtime, to the variables num1 and num2, respectively. Note In the preceding example, if you try to execute the statement, Calculator c1=new Calculator(); it would generate an error “No overload for method ‘Calculator’ takes ‘0’ argument”. NIIT Constructors and Destructors 6.7
  7. Implementing Destructors Destructors are special methods that are used to release the instance of a class from memory. A class can have only one destructor. The purpose of the destructor is to perform the required memory cleanup action. The programmer has no control on when to call the destructor. The .NET Framework automatically runs the destructor to destroy objects in the memory. Declaration of Destructors A destructor has the same name as its class but is prefixed with a ~, which is the symbol of tilde. Destructors cannot be inherited or overloaded. The following code modifies the declaration of the Calculator class by using a destructor: /* This code shows the use of destructor in the Calculator class */ using System; namespace Destructors { class Calculator { static int number1, number2, total; public void AddNumber() { total=number1+number2; Console.WriteLine("The Result is {0}", total); } Calculator () //Constructor { number1=20; number2=30; total=0; Console.WriteLine ("Constructor Invoked"); } ~Calculator () //Destructor { Console.WriteLine ("Destructor Invoked "); } static void Main(string[] args) { Calculator c1=new Calculator (); c1.AddNumber(); } } } 6.8 Constructors and Destructors NIIT
  8. In the preceding code, the .NET Framework automatically runs the destructor to destroy objects in the memory and displays the message “Destructor Invoked”. Note To see the output of the preceding program, press Ctrl+F5. The output of the preceding code is as follows. Output of the Calculator Class Program Even when you do not call the destructor, garbage collector releases memory. Garbage Collection Garbage collection is a process that automatically frees the memory of objects that are no more in use. The decision to invoke the destructor is made by a special program of C# known as the garbage collector. However, an object loses scope at the end of the Main () method, the destructor is not necessarily invoked. Therefore, in C#, you cannot determine when the destructor is called. Garbage collector also identifies the objects that are no more referenced in the program and releases the memory allocated to them. NIIT Constructors and Destructors 6.9
  9. In C#, you cannot destroy an object explicitly in code. In fact, it has the feature of garbage collection, which destroys the objects for the programmers. The process of garbage collection happens automatically. It ensures that: Objects get destroyed: It does not specify when the object shall be destroyed. Only unused objects are destroyed: An object is never destroyed if it holds the reference of another object. C# provides special methods that are used to release the instance of a class from memory, Finalize() and Dispose(). The Finalize() destructor is a special method that is called from the class to which it belongs or from the derived classes. The Finalize() destructor is called after the last reference to an object is released from the memory. The .NET Framework automatically runs the Finalize() destructor to destroy objects in the memory. However, it is important to remember that the Finalize() destructor may not execute immediately when an object loses scope. This is because the Common Language Runtime (CLR) calls the Finalize() destructor using a system called reference-tracing garbage collection. In reference-tracing garbage collection, the CLR periodically checks for objects that are not used by the application. When such an object is found, the Finalize() destructor is called automatically and the garbage collector of the CLR releases the object from the memory. The Dispose() method is called to release a resource, such as a database connection, as soon as the object using such a resource is no longer in use. Unlike the Finalize() destructor, the Dispose() method is not called automatically, and you must explicitly call it from a client application when an object is no longer needed. The IDisposable interface contains the Dispose() method. Therefore, to call the Dispose() method, the class must implement the IDisposable interface. Note An interface defines properties, methods, and events. Interface would be discussed in detail in Chapter 8. 6.10 Constructors and Destructors NIIT
  10. Identifying the Life Cycle of an Object The following code shows the life cycle of an object of the TestCalculator class: using System; //Life Cycle of an Object namespace Objects { class TestCalculator { TestCalculator() { Console.WriteLine("Constructor Invoked"); } ~TestCalculator() { Console.WriteLine("Destructor Invoked"); } public static void Main(string[] args) { Console.WriteLine("Main() Begins"); TestCalculator calc1 = new TestCalculator(); { Console.WriteLine("Inner Block Begins "); TestCalculator calc2 = new TestCalculator(); Console.WriteLine("Inner Block Ends"); } Console.WriteLine("Main() ends"); } } } Note To see the output of the preceding program, press Ctrl+F5. NIIT Constructors and Destructors 6.11
  11. The output of the preceding code is as follows. Output of the Life Cycle of Objects The explanation of the preceding output is as follows: The calc1 object has function scope. Therefore, its constructor is executed after the execution of Main () begins. The calc2 object has block scope. Therefore, its constructor is executed after the execution of the inner block begins. The destructor of all objects is invoked when garbage collector is invoked. 6.12 Constructors and Destructors NIIT
  12. Just a minute: Consider the following code snippet: Class Number { static mynumber; public void NumDisplay() { ... } static void Main(string[] args) { number n1=new number(); n1.NumDisplay(); Console.ReadLine(); } } The Number class has only one, static member variable called mynumber. Which constructor would you use to initialize mynumber? Answer: Static constructor NIIT Constructors and Destructors 6.13
  13. Practice Questions 1. Which of the following statement is true about garbage collection? a. In garbage collection the objects are not destroyed. b. In garbage collection the objects are destroyed every time. c. In garbage collection only unreferenced objects are destroyed. 2. A destructor has the same name as its class but is prefixed with ____________. 3. _______________ process identifies the unused objects and releases them in C#. 4. Consider the following code and identify which line will generate an error on compilation: using System; //Life Cycle of an Object namespace Objects { class Draw { public void Shape() { Console.WriteLine("in shape method"); } public Draw() // line 1 { Console.WriteLine("This is a constructor"); } public static void main(string[] arg) { Draw obj = new Draw(); obj.Draw(); // line 3 obj.Shape(); // line 4 } } } Consider the preceding code and answer the following question. Which line in the code will generate an error on compilation? a. line 1 b. line 2 c. line 3 d. line 4 5. The IDisposable interface contains the ____________ method. 6.14 Constructors and Destructors NIIT
  14. Summary In this chapter, you learned that: Constructors are member functions of a class and are invoked when an instance of the class to which they belong is created. A constructor has the same name as its class. A destructor is invoked when any instance of a class ceases to exist. A destructor has the same name as its class, but it is prefixed with a ~ (tilde). Constructors are special methods that allow control over the initialization of objects. Destructors are special methods that are used to release the instance of a class from memory. Garbage collection is a process that automatically frees the memory of objects that is no more in use. The Finalize() destructor is called after the last reference to an object is released from the memory. The Dispose() method is called to release a resource, such as a database connection, when the object using such a resource is no longer in use. NIIT Constructors and Destructors 6.15
  15. Exercises Exercise 1 Predict the output of the following program: using System; namespace Square_Number { class CalculateSquare { int number; public void Square(int number) { Console.WriteLine(number); number *= number; Console.WriteLine(number); } CalculateSquare() { number = 10; Square(number); } static void Main(string[] args) { CalculateSquare cal = new CalculateSquare(); Console.ReadLine(); } } } Exercise 2 Predict the output of the following program: using System; namespace CalculateNumber { class Calculate { static int number1; public void Display(int number) { Console.WriteLine(number); 6.16 Constructors and Destructors NIIT
  16. } Calculate() { number1++; Display(number1); } static Calculate() { number1 = 10; number1++; } static void Main(string[] args) { Calculate Cal1 = new Calculate(); Calculate Cal2 = new Calculate(); Console.ReadLine(); } } } NIIT Constructors and Destructors 6.17
  17. 6.18 Constructors and Destructors NIIT
ADSENSE

CÓ THỂ BẠN MUỐN DOWNLOAD

 

Đồng bộ tài khoản
2=>2