Introduction to the Constructors of a Class
Introduction to the Constructors of a Class
The Default Constructor
Introduction
A constructor of a class is a special method with two main rules and one primary feature:
Introduction to the Default Constructor
A constructor is a special method that is created when the object comes to life. When you create a class, if you don't create a constructor, the compiler creates one for you. This compiler-created constructor is called the default constructor. If you want, you can create your own default constructor.
To create a constructor, create a method that holds the same name as the class and that doesn't return any value. Here is an example:
public class Square
{
Square()
{
}
}
Remember that any method that doesn't have an access level is considered private. This is also valid for constructors. Although you can have private constructors in very extreme scenarios, most of the constructors you will create or use must be public (or internal). Here is an example:
public class Square
{
public Square()
{
}
}
If you are using Microsoft Visual Studio, to create a default constructor, right-click inside the class and click Insert Snippet... Double-click Visual C#. In the list that appears, double-click ctor. The Code Editor would use the name of the class to create the new constructor.
When you create an object of the class (by declaring a variable of that class), whether you use that object or not, a constructor for the object is created. When an instance of a class has been declared, the default constructor is called, whether the object is used or not.
Practical Learning: Using the Default Constructor
Initializing the Members of a Class
If a class has a default constructor, when an object is created from that class, that default constructor is automatically called. This feature makes the default constructor a good place to initialize the members of the class. You have many options.
When creating a class, you can declare a member variable and initialize it in the body of the class. Here are examples:
public class Element
{
int AtomicNumber = 1;
}
Remember that a member created without the access level (public, private, or internal) is treated as private, and to re-inforce this, you can precede the member with the private keyword:
public class Element
{
private int AtomicNumber = 1;
}
In the same way, you can declare and initialize as many members as you want in the body of the class. Here are examples:
public class Element
{
string Symbol = "H";
int AtomicNumber = 1;
}
As an alternative, you can fields in the class, then create a constructor and initialize the field(s) in the constructor.
Practical Learning: Creating a Constructor that Initializes
public class Element { public string ElementName; public string Symbol; public int AtomicNumber; public decimal AtomicWeight; public Element() { Symbol = "H"; AtomicNumber = 1; ElementName = "Hydrogen"; AtomicWeight = 1.008M; } }
Creating an Object Using a Constructor
As we should know already, to create an object, declare a variable of a class. As we mentioned already, if the class doesn't have any constructor or it has a default constructor, initialize the object using the default constructor. To access each member from the object variable, you can use the period operator.
Practical Learning: Creating an Object Using a Constructor
<!DOCTYPE html> <html> <head> <title>Chemistry - Hydrogen</title> </head> <body> @{ Element h = new Element(); } <div align="center"> <h2>Chemistry - Hydrogen</h2> <form name="frmChemistry" method="post"> <table> <tr> <td style="width: 120px; font-weight: bold">Symbol:</td> <td><input type="text" name="txtSymbol" value=@h.Symbol /></td> </tr> <tr> <td style="font-weight: bold">Element Name:</td> <td><input type="text" name="txtElementName" value=@h.ElementName /></td> </tr> <tr> <td style="font-weight: bold">Atomic Number:</td> <td><input type="text" name="txtAtomicNumber" value=@h.AtomicNumber /></td> </tr> <tr> <td style="font-weight: bold">Atomic Weight:</td> <td><input type="text" name="txtAtomicWeight" value=@h.AtomicWeight /></td> </tr> </table> </form> </div> </body> </html>
<!DOCTYPE html>
<html>
<head>
<title>Chemistry - Helium</title>
</head>
<body>
@{
Element he = new Element();
he.Symbol = "He";
he.ElementName = "Helium";
he.AtomicNumber = 2;
he.AtomicWeight = 4.002602M;
}
<div align="center">
<h2>Chemistry - Helium</h2>
<form name="frmChemistry" method="post">
<table>
<tr>
<td style="width: 120px; font-weight: bold">Symbol:</td>
<td><input type="text" name="txtSymbol" value=@he.Symbol /></td>
</tr>
<tr>
<td style="font-weight: bold">Element Name:</td>
<td><input type="text" name="txtElementName" value=@he.ElementName /></td>
</tr>
<tr>
<td style="font-weight: bold">Atomic Number:</td>
<td><input type="text" name="txtAtomicNumber" value=@he.AtomicNumber /></td>
</tr>
<tr>
<td style="font-weight: bold">Atomic Weight:</td>
<td><input type="text" name="txtAtomicWeight" value=@he.AtomicWeight /></td>
</tr>
</table>
</form>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Chemistry - Lithium</title>
</head>
<body>
@{
Element li = new Element() { ElementName = "Lithium", AtomicWeight = 6.94M, AtomicNumber = 3, Symbol = "Li" };
}
<div align="center">
<h2>Chemistry - Lithium</h2>
<form name="frmChemistry" method="post">
<table>
<tr>
<td style="width: 120px; font-weight: bold">Symbol:</td>
<td><input type="text" name="txtSymbol" value=@li.Symbol /></td>
</tr>
<tr>
<td style="font-weight: bold">Element Name:</td>
<td><input type="text" name="txtElementName" value=@li.ElementName /></td>
</tr>
<tr>
<td style="font-weight: bold">Atomic Number:</td>
<td><input type="text" name="txtAtomicNumber" value=@li.AtomicNumber /></td>
</tr>
<tr>
<td style="font-weight: bold">Atomic Weight:</td>
<td><input type="text" name="txtAtomicWeight" value=@li.AtomicWeight /></td>
</tr>
</table>
</form>
</div>
</body>
</html>
<!DOCTYPE html> <html> <head> <title>Chemistry - Beryllium</title> </head> <body> @{ Element be = new Element() { AtomicNumber = 4, ElementName = "Beryllium", AtomicWeight = 9.0121831M, Symbol = "Be" }; } <div align="center"> <h2>Chemistry - Beryllium</h2> <form name="frmChemistry" method="post"> <table> <tr> <td style="width: 120px; font-weight: bold">Symbol:</td> <td><input type="text" name="txtSymbol" value=@be.Symbol /></td> </tr> <tr> <td style="font-weight: bold">Element Name:</td> <td><input type="text" name="txtElementName" value=@be.ElementName /></td> </tr> <tr> <td style="font-weight: bold">Atomic Number:</td> <td><input type="text" name="txtAtomicNumber" value=@be.AtomicNumber /></td> </tr> <tr> <td style="font-weight: bold">Atomic Weight:</td> <td><input type="text" name="txtAtomicWeight" value=@be.AtomicWeight /></td> </tr> </table> </form> </div> </body> </html>
The Constructor as a Method
A Constructor with a Parameter
In your class, you can create a constructor that uses a parameter. Here is an example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
public class Square
{
public Square(decimal side)
{
}
}
In the body of the class, you can ignore or use the parameter. One way you can use it is to pass its value to a member variable of the class. Here is an example:
using System; using System.Collections.Generic; using System.Linq; using System.Web; public class Square { private decimal s; public Square(decimal side) { s = side; } }
Remember that the other members, such as methods, of the class can access any member of the same class. After creating the class, you can declare variables of it. If you create a class with only one constructor as in the above example, when declaring an instance of the class, you must use that constructor: you cannot use the default constructor that doesn't use a parameter. When declaring the variable, initialize it with a constructor with parentheses and provide the value(s) in the parentheses of the constructor.
Practical Learning: Using the Default Constructor
public class Square { private decimal s; public Square(decimal side) { s = side; } public decimal CalculatePerimeter() { return s * 4M; } public decimal CalculateArea() { return s * s; } }
<!DOCTYPE html> <html> <head> <title>Geometry - Square</title> </head> <body> @{ decimal area = 0M; decimal side = 0M; decimal perimeter = 0M; if (IsPost) { side = Request["txtSide"].AsDecimal(); Square sqr = new Square(side); perimeter = sqr.CalculatePerimeter(); area = sqr.CalculateArea(); } } <div align="center"> <h2>Geometry - Square</h2> <form name="frmGeometry" method="post"> <table> <tr> <td style="width: 120px; font-weight: bold">Side:</td> <td><input type="text" name="txtSide" value=@side /></td> <td><input type="submit" name="txtSubmit" value=Calculate /></td> </tr> <tr> <td style="font-weight: bold">Perimeter:</td> <td><input type="text" name="txtPerimeter" value=@perimeter /></td> <td> </td> </tr> <tr> <td style="font-weight: bold">Area:</td> <td><input type="text" name="txtArea" value=@area /></td> <td> </td> </tr> </table> </form> </div> </body> </html>
A Constructor with Many Parameters
In your class, you can create a constructor with as many parameters as you want. Here is an example of a constructor that uses three parameters:
public class Exercise
{
public Exercise(string a, int b, int c)
{
}
}
In the body of the constructor, you can ignore or use the values of the parameters. To create an object of the class, declare a variable of the class and initialize it using the constructor. This means that you must pass an argument for each parameter.
Practical Learning: Using a Constructor with Many Parameters
public class Element { public string Symbol; public string ElementName; public int AtomicNumber; public decimal AtomicWeight; public Element(int number, string symbol, string name, decimal mass) { Symbol = symbol; ElementName = name; AtomicWeight = mass; AtomicNumber = number; } }
<!DOCTYPE html> <html> <head> <title>Chemistry - Boron</title> </head> <body> @{ Element h = new Element(1, "H", "Hydrogen", 1.008M); Element he = new Element(2, "He", "Helium", 4.002602M); Element li = new Element(3, "Li", "Lithium", 6.94M); Element be = new Element(4, "Be", "Beryllium", 9.0121831M); Element b = new Element(5, "B", "Boron", 10.81M); } <div align="center"> <h2>Chemistry - Boron</h2> <form name="frmChemistry" method="post"> <table> <tr> <td style="width: 120px; font-weight: bold">Symbol:</td> <td><input type="text" name="txtSymbol" value=@b.Symbol /></td> </tr> <tr> <td style="font-weight: bold">Element Name:</td> <td><input type="text" name="txtElementName" value=@b.ElementName /></td> </tr> <tr> <td style="font-weight: bold">Atomic Number:</td> <td><input type="text" name="txtAtomicNumber" value=@b.AtomicNumber /></td> </tr> <tr> <td style="font-weight: bold">Atomic Weight:</td> <td><input type="text" name="txtAtomicWeight" value=@b.AtomicWeight /></td> </tr> </table> </form> </div> </body> </html>
Passing an Argument by Name
As seen with methods, if you call a constructor that takes many arguments, you can access each parameter by its name, followed by a colon, and its value.
Practical Learning: Passing Arguments by Names
<!DOCTYPE html> <html> <head> <title>Chemistry - Carbon</title> </head> <body> @{ Element h = new Element(1, "H", "Hydrogen", 1.008M); Element he = new Element(2, "He", "Helium", 4.002602M); Element li = new Element(3, "Li", "Lithium", 6.94M); Element be = new Element(4, "Be", "Beryllium", 9.0121831M); Element b = new Element(5, "B", "Boron", 10.81M); Element c = new Element(name: "Carbon", mass: 12.011M, symbol: "C", number: 6); } <div align="center"> <h2>Chemistry - Carbon</h2> <form name="frmChemistry" method="post"> <table> <tr> <td style="width: 120px; font-weight: bold">Symbol:</td> <td><input type="text" name="txtSymbol" value=@c.Symbol /></td> </tr> <tr> <td style="font-weight: bold">Element Name:</td> <td><input type="text" name="txtElementName" value=@c.ElementName /></td> </tr> <tr> <td style="font-weight: bold">Atomic Number:</td> <td><input type="text" name="txtAtomicNumber" value=@c.AtomicNumber /></td> </tr> <tr> <td style="font-weight: bold">Atomic Weight:</td> <td><input type="text" name="txtAtomicWeight" value=@c.AtomicWeight /></td> </tr> </table> </form> </div> </body> </html>
Constructor Overloading
In your class, you can create as many constructors as you want. If you decide to create different constructors, they must follow the rules of method overloading. This means that each constructor must be different from the others. To take care of this, each constructor can use a different number of parameters or different data types for parameters compared to other constructors. Here are examples:
public class Exercise
{
public Exercise(string a)
{
}
public Exercise(string a, int b, int c)
{
}
}
If you create different constructors, when declaring a (the) variable(s) for the class, you can choose what constructor is appropriate to initialize the variable.
Practical Learning: Passing Arguments by Names
public class Element
{
public string Symbol;
public string ElementName;
public int AtomicNumber;
public decimal AtomicWeight;
public Element(int number)
{
AtomicNumber = number;
}
public Element(string symbol)
{
Symbol = symbol;
}
public Element(int number, string symbol, string name, decimal mass)
{
Symbol = symbol;
ElementName = name;
AtomicWeight = mass;
AtomicNumber = number;
}
}
<!DOCTYPE html> <html> <head> <title>Chemistry - Nitrogen</title> </head> <body> @{ Element h = new Element(1, "H", "Hydrogen", 1.008M); Element he = new Element(2, "He", "Helium", 4.002602M); Element li = new Element(3, "Li", "Lithium", 6.94M); Element be = new Element(4, "Be", "Beryllium", 9.0121831M); Element b = new Element(5, "B", "Boron", 10.81M); Element c = new Element(name: "Carbon", mass: 12.011M, symbol: "C", number: 6); Element n = new Element(7); n.Symbol = "N"; n.AtomicWeight = 14.007M; n.ElementName = "Nitrogen"; } <div align="center"> <h2>Chemistry - Nitrogen</h2> <form name="frmChemistry" method="post"> <table> <tr> <td style="width: 120px; font-weight: bold">Symbol:</td> <td><input type="text" name="txtSymbol" value=@n.Symbol /></td> </tr> <tr> <td style="font-weight: bold">Element Name:</td> <td><input type="text" name="txtElementName" value=@n.ElementName /></td> </tr> <tr> <td style="font-weight: bold">Atomic Number:</td> <td><input type="text" name="txtAtomicNumber" value=@n.AtomicNumber /></td> </tr> <tr> <td style="font-weight: bold">Atomic Weight:</td> <td><input type="text" name="txtAtomicWeight" value=@n.AtomicWeight /></td> </tr> </table> </form> </div> </body> </html>
The Absence of a Default Constructor
If you create a class with only one constructor and that constructor uses at least one parameter, the default constructor would not be available anymore. If you want to access a default constructor of an object, you have two options:
A class is usually made to contain many members. The primary reason you create a constructor is to have a tool to initialize an object of the class with default values. The primary reason you create different constructors is to provide different values to objects depending on what constructor a user (actually a programmer) wants to use to create an object.
A Constructor with Default Values
Since a constructor is primarily a method, its parameter(s), if any, can use default values. The rules are exactly the same we reviewed for methods. To provide a default value for the parameter of a constructor, assign the desired but appropriate value to the parameter when creating the constructor. Here is an example:
public class Exercise
{
public Exercise(string caption = "Exercise")
{
}
}
Once again, in the body of the constructor, you can use or ignore the parameter. If you create one constructor and it uses one parameter, when creating an object of the class, that single constructor would act as both (or either) a default constructor and (or) a constructor that uses one parameter. This means that you can declare a variable and use a constructor with empty parentheses.
In the same way, you can create a constructor that uses different parameters and some parameters can have default values. When doing this, make sure you follow the rules we reviewed for methods that have default values for parameters.
As opposed to a constructor, a destructor is called when a program has finished using an object. A destructor does the cleaning behind the scenes. Like the default constructor, the compiler always creates a default destructor if you don't create one. Unlike the constructor, the destructor cannot be overloaded. This means that, if you decide to create a destructor, you can have only one. Like the default constructor, a destructor also has the same name as its class. This time, the name of the destructor starts with a tilde "~".
To create a destructor, type ~ followed by the name of the class. Here is an example:
public class Exercise
{
public Exercise(string caption = "Exercise", int width = 640, int height = 480)
{
}
~Exercise()
{
}
}
Practical Learning: Ending the Lesson
|
||
Previous | Copyright © 2001-2019, FunctionX | Next |
|