Monday, June 24, 2013

Constructors...




Difference between default constructor & empty constructor in java...

When we don't create a constructor Java creates a default constructor. But when we create one or more constructors Java doesn't create any default constructors... If we create one or more constructors and we want to create a object without any constructor We have to declare a empty constructor...
an example is shown below.... 

class Constructor{
 
    String name; //declaring attributes
    int age;
    String address;
    String school;
///////////////////////////////////
/*default constructor is something like this
    public Constructor()
    {    }             */
//////////////////////////////////
public Constructor(String name1,int age1){
    name = name1;
    age = age1;
    System.out.println("My name is: "+name);
    System.out.println("I am "+age+" years old.");
    
}
public Constructor(String address1){
    address = address1;
    System.out.println("My address is: "+address);
}

////////////////////////////////////
//When we creates constructors & if we want to make a object without constructor
//we have to declare a empty constructor...
public Constructor()
     {    }
///////////////////////////////////

public void school(String school1){
    
    school = school1;
    System.out.println("I studied at "+school+" .");

}
public static void main(String [] args){

    Constructor student = new Constructor("Manathunga",19);
    
    Constructor place = new Constructor("Colombo,Srilanka");
    
    
    Constructor empty = new Constructor();   //from empty constructor...
    empty.school("Sivali central college");
    
}
}

Hint : We put ( ) brackets after a object is created
          ex :  Constructor empty = new Constructor();
          We can put these brackets without any hesitation because 
          java makes a default constructor.But we can't see it...
          ex:   public Constructor()
                {             }

No comments:

Post a Comment