OOPS Corner : Instance Constructors
来源:互联网 发布:女神联盟星灵进阶数据 编辑:程序博客网 时间:2024/05/16 11:26
In this section we will see about instance constructors.
Instance Constructors
Instance constructors are responsible for setting an object instance to its initial state. Instance constructors of classes are invoked whenever an instance of a class is created.
Syntax of a simple instance constructor is as follows
ConstructorName()
{
...constructor body
}
Note that the name of the constructor should be same as that of the class and constructors cannot return any value not even void. Failing these conditions will result in a compiler error.
Example of an Instance Constructor is given below
class MyClass
{
public MyClass()
{
Console.WriteLine(“I am Constructor”);
}
}
Constructors can be overloaded meaning that a class can have several constructors with each constructor taking a different set of parameters as shown in sample below
class MyClass
{
public MyClass()
{
Console.WriteLine("No Parameter");
}
public MyClass(string param1)
{
Console.WriteLine("One Parameter");
}
public MyClass(string param1, int param2)
{
Console.WriteLine("Two Parameters");
}
}
If a class does not contain any instance constructor, a default parameter less instance constructor will be provided automatically. This default constructor will initialize the object fields to their default values.
Variable initializers are executed automatically before constructor body for example
class MyClass
{
int x=5;
int y;
public MyClass()
{
Console.WriteLine("X={0},Y={1}",x,y);
}
}
class startUP
{
publicstaticvoid Main()
{
MyClass MC=new MyClass();
}
}
will result in X=5,Y=0 as x is initialized to 5 and y is initialized to the default value of 0.
- OOPS Corner : Instance Constructors
- 8.7.8 Instance constructors
- 17.10 Instance constructors
- Constructors
- Constructors
- OOPS
- Oops~
- OOPS
- oops
- OOPS
- oops
- Chain Constructors
- understanding constructors
- C++ Constructors
- Custom Constructors
- Static Constructors
- CPP-Constructors
- instance
- Sun Microsystems’HotSpot JVM
- 馆学名流
- Getting Started with Reporting Services
- Extensible Applications: New Features Without Recompiling
- Using DataReaders to Increase Speed and Reduce Memory
- OOPS Corner : Instance Constructors
- Binary Serialization and BinaryFormatter with WebServices
- Accessibility Improvements in ASP.NET 2.0
- Using SQL Server for asp.net session state
- 女生教你如何追美媚
- DELPHI版块RAVE报表上解决的问题(zz)
- 我的第一篇BLOG
- 对于网上一些有关于Tapestry的一些资源
- ThreadLocal的设计与使用(转自 天极网)