Monday, 20 December 2010
What is Constructors?
Constructors is a special Member Function intialize the object of the classs.
Static classes and structs can also have constructors.
Whenever a class or struct is created, its constructor is called.
A class or struct may have multiple constructors that take different arguments.
Constructors enable the programmer to set default values, limit instantiation, and write code that is flexible and easy to read.
Constructor
A constructor is a special method whose task is to initialize the object of its class
It is special because its name is the same as the class name.
They do not have return types, not even void and therefore they cannot return values
They cannot be inherited, though a derived class can call the base class constructor.
Constructor is invoked whenever an object of its associated class is created.
Note: There is always atleast one constructor in every class.
If you do not write a constructor, C# automatically provides one for you, this is called default constructor. Eg: class A, default constructor is A().
Static Members of the class
Static members belong to the whole class rather than to individual object
Static members are accessed with the name of class rather than reference to objects.
Eg:
class Test
{
public int rollNo;
public int mathsMarks;
public static int totalMathMarks;
}
class TestDemo
{
public static void main()
{
Test stud1 = new Test();
stud1.rollNo = 1;
stud1.mathsMarks = 40;
stud2.rollNo = 2;
stud2.mathsMarks = 43;
Test.totalMathsMarks = stud1.mathsMarks + stud2.mathsMarks;
}
}
Labels:
OOPS
Subscribe to:
Post Comments (Atom)
hi sunjaiy. Very nice to study. Keep it up and update the question. Its may be useful for freshers
ReplyDelete