Gadgets

Monday, 25 February 2013

Constrauctor with example


Constructor:-
Constructor is a specialized method. Constructor name should be equals to class name.
 A constructor is similar to a method but Constructors doesn’t have return type (void, int,…).
A constructor does not return any value. A constructor is called & executed at the time of creating the object automatically. 
They two type of constructors
     1.       Default constructor:-
Class Student
{
Student()         //default constructor
               {
                     }
}
        2.       Parameterized constructor:-
Class Student
{
Student(par1,par2…)         //parameterized  constructor
               {
                     }
}

Example Program:-

public class Constructor_Example {
   
    public static void main(String args[])
    {
          Students ce= new Students();
          Students ce1= new Students(1214,"narendar");
         
    }
   
}
class Students{

    String collegename="VKITS";            // dynamic initialization
   
    Students(){            //default constructor
 
    System.out.println("default constructor");

}
    Students(int hno,String name)   //parameterized constructor
    {
        this.collegename=collegename;
       System.out.println("Student details : "+hno);
       System.out.println(name);
       System.out.println(collegename);
     }
}
Constructor overloading:-
Writing two or more constructors with same name with difference parameter is called constructor overloading.

No comments:

Post a Comment