1.

What is a default constructor? Does it take zero arguments. Is it correct?

Answer»

A default CONSTRUCTOR takes no arguments. Each object of the class is initialized with the default values that are specified in the default constructor. Therefore, it is not possible to initialize the DIFFERENT objects with different values.

An example that demonstrates a default constructor is given as follows:

USING System; namespace DefaultConstructorDemo {   class Sum   {     private int x;     private int y;     public Sum()     {         x = 5;         y = 7;     }     public int getSum()     {         return x + y;     }      }    class Test    {      STATIC void Main(STRING[] args)      {         Sum s = new Sum();            Console.WriteLine("Sum: {0}" , s.getSum());      }    } }

The output of the above program is as follows:

Sum: 12

Now let us understand the above program.

First, the class Sum is initialized. It contains two private variables x and y. The default constructor Sum() initializes x and y to 5 and 7 respectively. Then the function getSum() returns the sum of x and y. The code snippet for this is given below:

class Sum   {     private int x;     private int y;     public Sum()     {         x = 5;         y = 7;     }     public int getSum()     {         return x + y;     }    }

The main() function is in the class Test. It initializes an object s of class Sum. Then the sum of 5 and 7 is displayed using getSum(). The code snippet for this is given below:

class Test    {      static void Main(string[] args)      {         Sum s = new Sum();            Console.WriteLine("Sum: {0}" , s.getSum());      }    }


Discussion

No Comment Found