Constructor Overloading (or overloading constructors)

by kiranpvn kumar on 2/5/2012 11:19:29 PM
Rated 0 from 0 votes
Brief: This example demonstrates on how to define more than one constuctor in the class.
Posted to: Basics of Object Oriented Programming in .NET
Add to DiggAdd to del.icio.usAdd to FURLAdd to RedditAdd to YahooAdd to BlinklistAdd to GoogleAdd to ma.gnoliaAdd to ShadowsAdd to Technorati

A constructor is a special method which gets invoked implicitly.  We can have multiple constructors with difference in parameters called "Constructor Overloading"

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace ConstructorOverLoading
{
    class BankAccount
    {
        private int cust_id;
        private string cust_name;
        private int bal;
        public BankAccount()
        {
            cust_id = 1000;
            cust_name = "Not Yet Specified";
            bal = 0;
        }
        public BankAccount(int cust_id, string cust_name, int bal)
        {
            this.cust_id = cust_id;
            this.cust_name = cust_name;
            this.bal = bal;
        }
        public BankAccount(BankAccount obj)
        {
            cust_id = obj.cust_id;
            cust_name = obj.cust_name;
            bal = obj.bal;
        }
        public void ShowData()
        {
            Console.WriteLine("cust id = {0}, customer name = {1}, Bank Balance = {2}", cust_id, cust_name, bal);
        }
    }
    class Program
    {
        public static void Main(string[] args)
        {
            BankAccount a = new BankAccount();      // Invokes Default Constructor
            BankAccount b = new BankAccount(102,"Kiran", 5000 );    // Invokes Parameterized Constructor
            BankAccount c = new BankAccount(b);     // Invokes Copy Constructor
 
            a.ShowData();
            b.ShowData();
            c.ShowData();
 
        }
    }
}

Join the .NET Code Central Community and join the discussion!
Signing-up is FREE and quick. Do it now, we want to hear your opinion
0

Rated 0 from 0 votes ( login  to rate)
DotnetKicks DotnetKicksDe DotNetShoutout

Attachments / Source Code
You need to Login or Join for FREE to download the following