Constructor in Java

  1. Constructor name and  class name must be same.
  2. no  return type (int,float, void etc…..).
  3. It’s a special type of method that is used to initialize the object.
  4. 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:

  • college s=new college();

    Created the object for the class college.

  • s.student_information(); Using reference name s you are invoking the method student_information().

           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.

 

Posted on by