The simplest form of a class:
class Vehicle
{
}
But do not be misled by its simplicity. With this form, we could already instantiate an object:
Behind the scene, a default constructor is provided automatically for us if we do not defined one.
A constructor is a method with the same name as the Class. Eg Vehicle() for Vehicle Class.
As we could have many constructors, the one without any parameters – is called the default constructor.
When do we need to define the constructors and not depend on the auto generated default constructor?
Ans: When we need to do something such as providing initial values to data (initialization of data).
The following codes define a Vehicle Class and also a main() (in Program class) to test the class:
// A class with a public variable, default constructor and overload constructor
class Vehicle
{
public string colour;
// Default constructor to set colour
public Vehicle()
{
colour = "Gray";
}
// Another constructor to take in a parameter
// Overloading - same method name but different parameters
public Vehicle(string col)
{
colour = col;
}
// Destructor called by Garbage Collection (GC)
// not required most of the time as GC can do better object release than us
~Vehicle()
{
}
}
class Program
{
static void Main(string[])
{
Vehicle car = new Vehicle();
Vehicle car2 = new Vehicle("Red");
Console.WriteLine(car.colour);
Console.WriteLine(car2.colour);
Console.ReadKey();
}
}
0 comments:
Post a Comment