- Constructor name and class name must be same.
- no return type (int,float, void etc…..).
- It’s a special type of method that is used to initialize the object.
- when you are creating the object for the class then constructor wil be invoked.
public class college
{
int id;
String sname;
String coll;
public college()
{
System.out.println("welcome to construcor concept");
}
public college(int i)
{
id = i;
}
college( String k,String d)
{
sname=k;
coll=d;
}
voidstudentid()
{
System.out.println("student id :"+id);
}
voidstudent_name_coll()
{
System.out.println("name and coll :"+sname+" "+coll);
}
public static void main(String args[])
{
college s=new college();
college s1=new college(10);
college s2=new college("karthik","VVIET");
s1.studentid();
s2.student_name_coll();
}
}
Output:
welcome to construcor concept
student id :10
name and coll :karthik VVIET
points:
- when you are creating an object for the class, default constructor (or no argument constructor) will be called ( college s=new college();). then it wil print welcome to construcor concept.
- college s1=new college(10); (one argument constructor wil be invoked).Value 10 stored in local variable i , then it stored to instance variable id.
- college s2=new college("karthik","VVIET");two argument constructor wil be invoked, value karthik and VVIET stored in local variable k and d;then it assigned to instance variable of the class sname and coll.
- s1.studentid();with the help of the reference name s1 we are calling the method namestudentid();then it wil print student id :10.
- s2.student_name_coll();with the help of the reference name s2 we are calling the method namestudent_name_coll().then it wil print name and coll :karthik VVIET.
public class college
{
int id;
String sname;
String coll;
voidstudent_information()
{
System.out.println("student id :"+id);
System.out.println("name and coll :"+sname+" "+coll);
}
public static void main(String args[])
{
college s=new college();
s.student_information();
}
}
Output:
student id :0
name and coll :null null
points:
Here you have not created any constructor so compiler gives you a default constructor.
Task of default constructor is to provide 0(zero) for id, null for name and coll.