Constructors are class methods that are executed when an object of a given type is created. Constructors have the same name as the class, and usually initialize the data members of the new object.
In the following example, a class called Taxi is defined with a simple constructor. This class is then instantiated with the new operator. The Taxi constructor is invoked by the new operator immediately after memory is allocated for the new object.
public class Taxi
{
public bool isInitialized;
public Taxi()
{
isInitialized = true;
}
}
class TestTaxi
{
static void Main()
{
Taxi t = new Taxi();
System.Console.WriteLine(t.isInitialized);
}
} A constructor that takes no parameters is called a default constructor.Default constructors are invoked whenever an object is instantiated using the new operator and no arguments are provided to new Passing Arguments to Constructors Constructors may also be used to pass in initial values for an object's attributesat the time that an object is being instantiated. Instead of creating an object whoseattributes are all initialized to zero-equivalent values, and then utilizing the accessorsprovided by that class to initialize attribute values one-by-one, as illustratedby the next snippet: //Create a bare boones Student onject Student s = new Student(); //Initialize the atributes one-by-one s.name = "Ivan Osorio"; s.ssn = "06210056"; s.major = "English"; the initial values for selected attibutes can all passed in as a single step whenthe constructor is called, if desired:
Student s = new Student("Ivan Osorio", "06210056", "English");
In order to accommodate this, we'd have to define a Student constructor with anappropriate header, as shown here:
public class Student { //Atributes private string name; private string ssn; private straing major; /* We've programmed a constructor with three parameters to accommodate passing in argument values. */
public Student (string s, string n, string m) { name = n; ssn = s; major = m; } }
No comments:
Post a Comment