Feb 16, 2012

Working with Constructors

In Java, When we  are creating a new instance of the class, the constructor of the class will be called. If a class doesn't have a constructor then it will assume there's a default constructor. But constructors are used to assign some initial values  to class fields.
Ex:
public class Employee{


  private int empID;

  private String name;


   public Employee(){
    this.empID = 1
    this.name = "Un-defined"
   }
}
We all know that we cant have two constructor in a class, with the same name and same parameters but a different data-type. But while i m analyzing this limitation, suddenly a doubt arise to me whether we can have two constructors with a single parameter, but the data Type of these parameters are different.

Ex:

public class Employee{


// Constructor 1
   public Employee(int empID){
   }


// Constructor 2

  public Employee(String name){
   }



}

No comments:

Post a Comment

Post a Comment

Note: Only a member of this blog may post a comment.