Introduction to the Constructors of a Class
Introduction to the Constructors of a Class
Introduction to Constructors
Introduction to the Constructor of a Class
When you create an object (a variable declared from a class), you are in fact describing an object. In some cases, you may want that object to hold some default characteristics so that you don't have to work from scratch. A constructor is a special method that specifies the primary information of an object.
Practical Learning: Introducing Constructors
namespace Quadrilaterals1.Pages { public class Square { public double _side_; public double CalculatePerimeter() { return _side_ * 4; } public double CalculateArea() { return _side_ * _side_; } } }
Creating a Constructor
A constructor is created as a special method with two main rules and one primary feature:
Here is an example of creating a constructor in a class named Square:
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:
class Square
{
public Square()
{
}
}
As we saw in the previous lessons, a class can have various types of members (such as fields, properties, and methods). Here is an example of a class that has some fields and a constructor:
class House
{
public House()
{
}
public string type;
public int beds;
public double value;
}
In the body of a class, the order of appearance of the members is not important. This means that you can first create a constructor followed by other members, first the members and a constructor last, or a constructor between members. Here is an example:
public class House
{
public int propNumber;
public double baths;
public House()
{
}
public string type
public int beds;
public double value;
}
A Constructor with a Parameter
In your class, you can create a constructor that uses a parameter. Here is an example:
public class Square
{
public Square(double 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:
public class Square { private double s; public Square(double 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.
Creating an Object
Calling a Constructor
Consider a class we saw above:
public class House { public string type; public int beds; public double value; }
From our introductions, we know that, when declaring a variable of a class type, after the new operator, you must write the name of the class followed by parentheses. Here is an example we saw already:
@page
@model Valuable.Pages.FoundationsModel
@{
House residence = new House();
}
In reality, when you declare a variable like that, you are actually calling the constructor of the class. As a result, the primary role of a constructor is to provide the default characteristics of an object created from a class. Therefore, in the body of a constructor, you can access each field and assign the desired value to it. Here is an example:
class House
{
public string type;
public int beds;
public double value;
public House()
{
type = "Single-Family";
beds = 5;
value = 495_680;
}
}
Practical Learning: Introducing Constructors
namespace Quadrilaterals1.Pages
{
public class Square
{
public double _side_;
public Square(double side)
{
_side_ = side;
}
public double CalculatePerimeter()
{
return _side_ * 4;
}
public double CalculateArea()
{
return _side_ * _side_;
}
}
}
@page @model Quadrilaterals1.Pages.GeometryModel @{ double side = 248.73; Square sqr = new Square(side); } <pre>===================================== Geometry - Square Summary ------------------------------------- Perimeter: @sqr.CalculatePerimeter() Area: @sqr.CalculateArea() =====================================</pre>
===================================== Geometry - Square Summary ------------------------------------- Perimeter: 994.92 Area: 61866.61289999999 =====================================
An Object Without a Constructor
There are various ways to create an object. The most classic way is to start with the name of a class, assign the new operator followed by the name of the class again. Here is an example:
@page
@model Quadrilaterals1.Pages.GeometryModel
@{
Trapezoid trap = new Trapezoid();
trap.bottom = 1159.73;
trap.top = 736.86;
trap.height = 552.94;
}
@functions{
public class Trapezoid
{
public double bottom;
public double height;
public double top;
public Trapezoid()
{
bottom = 0.00;
height = 0.00;
}
public double CalculateArea()
{
return ((bottom + top) / 2.00) * height;
}
}
}
<pre>Trapezoid
---------------------------
Top: @trap.top
Bottom: @trap.bottom
Height: @trap.height
---------------------------
Area: @trap.CalculateArea()</pre>
This would produce:
Trapezoid --------------------------- Top: 736.86 Bottom: 1159.73 Height: 552.94 --------------------------- Area: 524350.2373
When you use this technique, you can omit the constructor on the right side of the assignment operator. Here is an example:
@page
@model Valuable.Pages.ExerciseModel
@{
Trapezoid trap = new();
// . . .
}
@functions
{
public class Trapezoid
{
}
}
A Variable Object
When you are creating an object, you can omit the constructor on the left side of the assignment operator. In this case, you can replace the constructor with the var keyword. Also in this case, you must use the constructor on the right side of the assignment operator. Besides the var operator, you can also use the dynamic keyword. Here are examples:
@page @model Quadrilaterals1.Pages.GeometryModel @{ // A variable object var trap = new Trapezoid(); // A dynamic object dynamic zoid = new Trapezoid(); trap.bottom = 1159.73; trap.top = 736.86; trap.height = 552.94; zoid.bottom = 318.67; zoid.top = 526.36; zoid.height = 705.71; } @functions{ public class Trapezoid { public double bottom; public double height; public double top; public Trapezoid() { bottom = 0.00; height = 0.00; } public double CalculateArea() { return ((bottom + top) / 2.00) * height; } } } <pre>Trapezoid --------------------------- Top: @trap.top Bottom: @trap.bottom Height: @trap.height --------------------------- Area: @trap.CalculateArea() =========================== Trapezoid --------------------------- Top: @zoid.top Bottom: @zoid.bottom Height: @zoid.height --------------------------- Area: @zoid.CalculateArea()</pre>
This would produce:
Trapezoid --------------------------- Top: 736.86 Bottom: 1159.73 Height: 552.94 --------------------------- Area: 524350.2373 =========================== Trapezoid --------------------------- Top: 526.36 Bottom: 318.67 Height: 705.71 --------------------------- Area: 298173.06065
The Default Constructor
Introduction
We know that we can create a class without adding a constructor to it. Here is an example:
class House { string location; string floorPlan; int basement; }
When you set up a class, if you don't add a constructor, the compiler creates one for you. Whether you create this constructor or the compiler creates it for you, the constructor with empty parentheses is called the default constructor. If you want, you can create your own default constructor. To explicitly create a default constructor, create a method that holds the same name as the class and leave the parentheses of that constructor empty. Here is an example:
@functions
{
class House
{
public House()
{
}
}
}
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 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. You may find it sometimes convenient to create your own constructor because, whether you create a default constructor or not, this does not negatively impact your program.
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 is an example:
@functions
{
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-enforce this, you can precede the member with the private keyword:
@functions
{
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:
@functions
{
public class Element
{
string symbol = "H";
int atomicNumber = 1;
}
}
As an alternative, you can create fields in the class, then create a constructor and initialize the field(s) in the constructor.
Creating an Object Using a Constructor
As we have seen in previous lessons, to create an object, declare a variable of a class. As we saw in previous and in this lessons, if the class doesn't have any constructor or it has a default constructor, initialize the object using the default constructor. When accessing each member from the object variable, you can use the period operator.
Initializing an Object
With or without a constructor, you can specify the values of an object at any time. This means that, even if a class has a default constructor and you have created its object, to set the values of the members of the class, access each member and assign the desired value.
The Constructor as a Method
A Constructor with 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:
@functions{
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.
Passing an Argument by Name
As seen with methods, if you call a constructor that takes at least one argument, you can access the/each parameter by its name, followed by a colon, and its value. Here is an example:
@page
@model Valuable.Pages.ExerciseModel
@{
Element c = new(name: "Carbon", mass: 12.011, symbol: "C", number: 6);
}
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:
@functions{
public class Exercise
{
public Exercise(string a)
{
}
public Exercise(string a, int b, int c)
{
}
}
}
If you have different constructors, when creating (an) instance(s) of the class (when declaring a (the) variable(s) of the class), you can choose what constructor is appropriate to initialize the variable.
Consider the following class and its constructor:
@functions{ public class Element { string _name_; string _symbol_; int _number_; double _weight_; public Element(int number, string symbol, string name, double mass) { _name_ = name; _weight_ = mass; _symbol_ = symbol; _number_ = number; } } }
If you create a class with only one constructor, when declaring an instance of the class, you must use that constructor: you cannot use the default constructor that doesn't use any parameter. When declaring the variable, initialize it with a constructor with parentheses and provide the value(s) in the parentheses of the constructor.
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:
@functions{
public class Exercise
{
public Exercise()
{
}
public Exercise(string caption)
{
}
public Exercise(string caption, int width, int height)
{
}
}
}
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 one or some 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. To make this happen, you can initialize the members with values passed to the parameter(s).
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:
@functions{
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. Here is an example:
@page
@model Valuable.Pages.ExerciseModel
@{
Employee staff = new Employee();
}
@functions{
public class Employee
{
public Employee(string name = "John Doe")
{
}
}
}
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 functions (or methods) that have default values for parameters.
The Destruction of an Object
A destructor is a special method of a class. While a constructor is called when an object is created, a destructor is called when an object is not used anymore. The job of a destructor is to do the cleaning of the computer memory that an object was occupying when the object was used. 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() { } }
When you initialize a variable using the new operator, you are in fact reserving some space in the section of memory called the heap. Such memory is "allocated" for the variable. When that variable is no longer needed, such as when your program closes, the variable must be removed from memory and the space it was using should (must) be made available to other variables or other programs. In fact, when an object has been removed from memory, it is replaced by garbage, which is some value but that is of no use (that area of memory becomes filled with garbage). If you program in some languages such as C/C++, Assembly, Pascal, etc, you should (must) find a way to remove that garbage (it is not difficult, sometimes it takes a simple/single line of code, but you should (must) remember to do it); that is, you should (must) free the memory a variable (declared with new, and called a reference) was using. Freeing the memory is referred to as garbage collection. Normally, in languages like C++ or Pascal, that's one of the ways you use a destructor.
The .NET library solves the problem of garbage collection by "cleaning" the memory after you. This is done automatically when necessary so that the programmer doesn't need to worry about this issue.
Practical Learning: Ending the Lesson
|
|||
Previous | Copyright © 2001-2022, C# Key | Monday 27 December 2021 | Next |
|