Constructor is also a method of class like other methods. But it is only invoked or called when an instance or object of the class is created. When memory is allocated successfully for that object, a constructor is called. It is used to initialize the attributes or member variables for that object. For example if we have a student class and want to assign 25 marks initially, when user didn't entered the marks. We will use constructor to assign this default value.
1. Constructor must have the same name as the class have.
2. Constructor must NOT have any return type. It even can't be void. So just write public or private before the name and then class name and the (). In Brackets you can have parameter.
3. If you don't write any constructor, a default constructor is called. That default constructor is always be parameter less and it will do nothing.
4. You can more than one constructor also. For example one constructor takes no arguments, second takes one and third takes two arguments. This is called constructor overloading.
Here are examples of constructor.
public class Student{
public Student()
{
}
public Student(int age)
{
}
public Student(int age, int marks)
{
}
}
I have not shown the rest of the code of class. It same as the previous one. Now when you create the object of the class, one of these constructor is called depending upon the number of arguments. See below examples.
Student S1 = new Student(); // first parameter less constructor will be called.
Student S2 = new Student(20); // second constructor will be called.
Student S1 = new Student(20, 78); // third constructor will be called.
That's the end of today's class. Next we will discuss garbage collection INSHALLAH.
No comments:
Post a Comment