Constructors are used to initialize the object.
Constructors have the same name with the class but their return types are empty.
class Rectangle{
public Rectangle(){
}
}
Constructors can have parameters.
The following code uses the contructor to initialize the fields.
using System;
class Rectangle{
public int Width;
public int Height;
public Rectangle(int w, int h){
Width = w;
Height = h;
}
}
class Program
{
static void Main(string[] args)
{
Rectangle r = new Rectangle(1, 2);
Console.WriteLine(r.Width);
}
}
The output:
1
Constructors can have the following modifiers:
java2s.com | Contact Us | Privacy Policy |
Copyright 2009 - 12 Demo Source and Support. All rights reserved. |
All other trademarks are property of their respective owners. |