Presentation is loading. Please wait.

Presentation is loading. Please wait.

Static data members Constructors and Destructors

Similar presentations


Presentation on theme: "Static data members Constructors and Destructors"— Presentation transcript:

1 Static data members Constructors and Destructors
Lecture # 4

2 Content Static data members Constructors : definition, types
Destructors

3 Static Data Members A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated. In other words, you cannot use the new keyword to create a variable of the class type. Because there is no instance variable, you access the members of a static class by using the class name itself.

4 Static Data Members A C# class can contain both static and non-static members. When we declare a member with the help of the keyword static, it becomes a static member. A static member belongs to the class rather than to the objects of the class. Hence static members are also known as class members and non-static members are known as instance members.

5 Static Class A static class can be used as a convenient container for sets of methods that just operate on input parameters and do not have to get or set any internal instance fields. For example, in the .NET Framework Class Library, the static System.Math class contains methods that perform mathematical operations, without any requirement to store or retrieve data that is unique to a particular instance of the Math class.

6 Example That is, you apply the members of the class by specifying the class name and the method name, as shown in the following example. double dub = -3.14; Console.WriteLine(Math.Abs(dub)); Console.WriteLine(Math.Floor(dub)); Console.WriteLine(Math.Round(Math.Abs(dub)));

7 Contd.. The following list provides the main features of a static class: Contains only static members. Cannot be instantiated. Is sealed. Cannot contain Instance Constructors.

8 Contd.. They are slightly faster than instance methods because of this. Static methods can be public or private. private static string companyName = "Microsoft"; private string name; When you use a static field, you associate it with the class name rather than a particular object: Console.WriteLine("Company Name: {0}", Employee.CompanyName); This leads to classifying the class members into two categories: Instance members Static members

9 Code public class Automobile { public static int NumberOfWheels = 4; public static void Drive() //Some Statements } Main Method Automobile.Drive(); int i = Automobile.NumberOfWheels;

10 Some Points to Ponder The static member is callable on a class even when no instance of the class has been created. The static member is always accessed by the class name, not the instance name.  Static methods only use static data members to perform calculation or processing. Static methods can be overloaded but not overridden, because they belong to the class, and not to any instance of the class C# does not support static local variables (variables that are declared in method scope).s.

11 Constructor Whenever a class or struct is created, its constructor is called. A class or struct may have multiple constructors that take different arguments. Constructor is a special method of a class which will invoke automatically whenever instance or object of class is created. Constructors are responsible for object initialization and memory allocation of its class. If we create any class without constructor, the compiler will automatically create one default constructor for that class. There is always at least one constructor in every class If you do not provide a constructor for your object, C# will create one by default that instantiates the object and sets member variables to the default values

12 Constructor Classes are conceptual units. With them we construct object models. And constructors are specialized methods that have runtime support to create instances of classes for these models. Constructor looks like the other methods in a class declaration, with the following exceptions: The name of the constructor is the same as the name of the class. A constructor cannot have a return value

13 Constructors Constructors are special methods, used when instantiating a class. A constructor can never return anything, which is why you don't have to define a return type for it. A normal method is defined like this: public string Describe() { // statements } A constructor can be defined like this: public Describe() { // constructor code }

14 Types of Constructors Basically constructors are 5 types those are 1. Default Constructor 2. Parameterized Constructor 3. Copy Constructor 4. Static Constructor 5. Private Constructor

15 Default Constructor All classes have constructors, whether you define one or not, because C# automatically provides a default constructor that causes all member variables to be initialized to their default values. For most value types, the default value is zero. For bool, the default is false. For reference types, the default is null. However, once you define your own constructor, the default constructor is no longer used. However, once you define your own constructor, the default constructor is no longer used.

16 A simple constructor. class MyData { public int Id; public MyData () {
class Program { static void Main() { MyData a = new MyData(); MyData b = new MyData(); Console.WriteLine(a.Id + " " + b.Id); }

17 Another Example Class Sample { public string line1, line2;
public Sample()     // Default Constructor line1 = "Welcome"; line2 = “User"; }

18 Contd.. class Program { static void Main(string[] args)
Sample obj=new Sample();    // Once object of class created automatically constructor will be called Console.WriteLine(obj. line1); Console.WriteLine(obj. line2); Console.ReadLine(); } OUTPUT Welcome User

19 Parameterized Constructors
A constructor with at least one parameter is called as parameterized constructor. In parameterized constructor we can initialize each instance of the class to different values like as shown below

20 Code Class Sample { public string param1, param2;
public Sample(string x, string y)      // Declaring Parameterized constructor with Parameters param1 = x; param2 = y; }

21 Code Contd.. class Program { static void Main(string[] args)
Sample obj=new Sample(“This is",Theory Class");     // Parameterized Constructor Called Console.WriteLine(obj.param1 +" our "+ obj.param2); Console.ReadLine(); }

22 Constructor Overloading
In c# we can overload constructor by creating another constructor with same name and different parameters. First we will discuss the purpose of constructor overloading; it's very important to have the clear understating of the preceding topic. There are many complex conditions that exist when designing OOP models and we need to initialize a different set of member variables for different purposes of a class. So we need to use constructor overloading

23 Contd.. The definition of constructor overloading is:
Just like member functions, constructors can also be overloaded in a class. The overloaded constructor must differ in their number of arguments and/or type of arguments and/or order of arguments.

24 Constructor Overloading :
C# supports overloading of constructors, that means we can have constructors with different set of parameters. So our class can be like this : public class mySampleClass { public mySampleClass() { // This is the no parameter constructor method. // First Constructor } public mySampleClass(int Age) { // This is the constructor with one parameter. // Second Constructor } public mySampleClass(int Age, string Name) { // This is the constructor with two parameters. // Third Constructor } // rest of the class members goes here. } 

25 Code Contd.. Well, note here that call to the constructor now depends on the way you instantiate the object. For example : `mySampleClass obj = new mySampleClass() // At this time the code of no parameter  // constructor (First Constructor) will be executed mySampleClass obj = new mySampleClass(12) // At this time the code of one parameter  // constructor(Second Constructor) will be  // executed.

26 Private Constructors A constructor becomes a private constructor when we declare it with the private access specifier. As we know, the private access modifier is a bit of a special case. We neither create the object of the class, nor can we inherit the class with only private constructors. But yes, we can have the set of public constructors along with the private constructors in the class and the public constructors can access the private constructors from within the class through constructor chaining. Private constructors are commonly used in classes that contain only static members. The main purpose of creating private constructor is used to restrict the class from being instantiated when it contains every member as static.

27 Code class car { public string carname; private car() { carname = ”Jeep”; } public car(int model):this() { Console.WriteLine("Model Year:{0}",model); Console.WriteLine("Maker Name:{0}",carname); } } }} static void Main(string[] args) { car sportscar = new car(2013); Console.ReadKey(); } This is a very simple example of private constructors in which we use a public constructor to call the private constructor.

28 Important points of private constructor
One use of private construct is when we have only static member. If we want to create object of class even if we have private constructors then we need to have public constructor along with private constructor

29 Constructors Chaining
When a constructor invokes another constructor in the same class or in the base class of this class it is known as constructor chaining. It is a very useful technique for avoiding code duplication.

30 Constructors Chaining
The following describes Constructor Chaining: A constructor can call another constructor of the same class or of the base class Since one constructor can invoke another, this sometimes can cause the execution of multiple constructors; that is referred to as Constructor Chaining. If a class is not derived from any other class then the following would be the chain:  Static Constructor.  Instance Constructor

31 Constructors Chaining
If a class is derived from any other class then the following would be the chain:   Derived Static Constructor.   Base Static Constructor.  Base Instance Constructor. Derived Instance Constructor.

32

33 Main Method

34 Static Constructors You can create a constructor as static and when a constructor is created as static, it will be invoked only once for any number of instances of the class and it is during the creation of first instance of the class or the first reference to a static member in the class. Static constructor is used to initialize static fields of the class and to write the code that needs to be executed only once. A static constructor initializes static fields. It runs at an indeterminate time before those fields are used. Static constructors on a type  To initialize a Static Class or static variables in a non-static class, Static Constructors are used. Access Modifiers are not allowed on Static Constructors.

35 Static Constructors Static Constructors cannot be parameterized.
There can be only one Static Constructor per class. Static Constructors cannot have an explicit "this" or "base" constructor call, in other words Static Constructors cannot be called directly. Static Constructors are called automatically before the first instance of a class is created or any static member is referenced. Static Constructors are called only once in the lifetime of a class

36 Example Class DemoClass { Static DemoClass() {
{       Static DemoClass()       {           //code inside this constructor       }   }   Static constructor is basically used to initialize the static fields and properties of the class. There should at most one Static Constructor in a class and also Static Constructor can't take any parameters.

37 Static Constructor Things to know about Static Constructor
It is used to initialize static data members.  Can't access anything but static members. Can't have parameters Can't have access modifiers like Public, Private or Protected.

38 Points to Ponder Some unique points related to constructors are as follows A class can have any number of constructors. A constructor doesn’t have any return type even void. A static constructor can not be a parameterized constructor. Within a class you can create only one static constructor.

39 Destructors Since C# is garbage collected, meaning that the framework will free the objects that you no longer use, there may be times where you need to do some manual cleanup. A destructor, a method called once an object is disposed, can be used to cleanup resources used by the object. Destructors doesn't look very much like other methods in C#.

40 Destructors Here is an example of a destructor for our Car class:
{ Console.WriteLine("Out.."); } Once the object is collected by the garbage collector, this method is called.


Download ppt "Static data members Constructors and Destructors"

Similar presentations


Ads by Google