Constructor
Constructor rules:
- Constructor has the same name as the class in which it locate.
- Constructors have no return type, not even void.
- This is because type of a class
constructor is the class type itself.
Here constructor of Student class.
class Student{
string name;
int age;
//Here Default constructor or without parameter
Student(){
name="abc";
age=20;
}
}
When we don’t clearly define a constructor for a class,
then Java creates a default constructor for the class.
The default constructor
automatically initializes all instance variables to zero.
Once we define our own constructor,
the default constructor is no longer used in class.
Parameterized Constructor:
class Student{
string name;
int age;
//Here constructor
Student(string n,int a){
name=n;
age=a;
}
}
Comments
Post a Comment