7.3. Instance constructors

Instance constructors in C# are simply Java constructors. The reason for the name is because there is another group of constructors in C# called static constructors (see section 7.4).

Here is an example of a class with overloaded instance constructors.

 1: using System;
 2:
 3: public class Test{
 4:   public static void Main(){
 5:     Test t1 = new Test();
 6:     Test t2 = new Test("Here is a string");
 7:   }
 8:
 9:   // overloaded instance constructors
10:   public Test(){
11:     Console.WriteLine("Running default constructor");
12:   }
13:   public Test(string i){
14:     Console.WriteLine("Running constructor with param");
15:   }
16: }

Output:

c:expt>test
Running default constructor
Running constructor with param

Like Java

  • Instance constructors must have the same name (and case) as the immediately enclosing class, and cannot return a value.

  • Constructors are special methods of a class that will always be called when an instance of that class is first created.

  • The rule of constructor chaining still applies – invoking the constructor of a class always invokes the constructor of its superclass recursively all the way to System.Object.

  • Unlike other methods, constructors are not inherited to subclasses.

  • You can overload constructors.

  • A default constructor [5] is provided if no constructor is explicitly coded in the class. However, when at least one constructor is coded in a class, the default constructor will not be provided implicitly.

    [5] A default constructor refers to the constructor which takes in no parameters.

  • You can use the this keyword to invoke an overloaded constructor in the same class (see section 7.6).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.91.47