Friday, 31 May 2013

Constructors in JAVA

A class contains constructors that are invoked to create objects from the class blueprint. Constructor declarations look like method declarations—except that they use the name of the class and have no return type.

Example: class MotorBike has one constructor as follows.

public MotorBike(int startGear, int startSpeed){
 gear = startGear;
 speed = startSpeed;
}

To create a new MotorBike object called motorBike a constructor is called by the new operator:

MotorBike motorBike = new MotorBike(1, 20);

new MotorBike(1, 20) creates space in memory for the object and initializes its fields.

Although MotorBike only has one constructor, it could have others, including a no-argument constructor:

public MotorBike() {
    gear = 1;
    speed = 0;
}

MotorBike yourBike = new MotorBike(); invokes the no-argument constructor to create a new MotorBike object called yourBike.

NOTE: Both constructors could have been declared in MotorBike because they have different argument lists. As with methods, the Java platform differentiates constructors on the basis of the number of arguments in the list and their types. We cannot write two constructors that have the same number and type of arguments for the same class, because the platform would not be able to tell them apart.

Rules for constructors:
  • A java constructor has the same name as the name of the class to which it belongs. Constructor’s syntax does not include a return type, since constructors never return a value. 
  • Constructors may include parameters of various types. When the constructor is invoked using the new operator, the types must match those that are specified in the constructor definition.
  • When the object is created, Java calls the constructor first. Any code you have in your constructor will then get executed. You don't need to make any special calls to a constructor method - they happen automatically when you create a new object.
  • We cannot write two constructors that have the same number and type of arguments for the same class.
NOTE: You don't have to provide any constructors for your class, but you must be careful when doing this. The compiler automatically provides a no-argument, default constructor for any class without constructors. This default constructor will call the no-argument constructor of the superclass. In this situation, the compiler will complain if the superclass doesn't have a no-argument constructor so you must verify that it does. If your class has no explicit superclass, then it has an implicit superclass of Object, which does have a no-argument constructor.

Why should we use Constructors:
  • When we create new instance(new object) of class using new keyword, a constructor for that class is called.
  • Constructors are used to initialize the instance variables of an object. 
  • A constructor must have the same name as the class its in.
  • Default Constructor: If we do not define a constructor for a class, a default constructor with out parameters is automatically created by compiler.
  • Default constructor calls the default constructor of parent class (using super() keyword) and initialize the all instance variables to default values(zero for numeric types, null for object references and false for Boolean).
  • Default constructor is created only if there are no constructors. If we define any constructor for our class, no default constructor is automatically created.

Why a constructor does not return a value?

As per my knowledge what actually happens with constructor is that  run time uses the type data generated by the compiler to determine how much space is needed to store an object instance in memory, be it on the stack or on the heap. This space includes all member variables. After this space is allocated, the constructor is called as an internal part the instantiation and initialization process to initialize the contents of the fields. Then, when constructor exits, the runtime returns the newly created instance. So the reason for the constructor does not return a value is "it is not called directly by our code, it is called by the memory allocation and object initialization code in run time". Its return value(if it actually has one when compiled down to machine code) is opaque to the user- therefore, we can not specify the return value for constructor.

Constructor Example:

public class ConstructorExample {
int num1;
int num2;
String firstName;
String lastName;

 //explicitly defined default constructor 
 public ConstructorExample() {
System.out.println("Default constructor");
}

 // Constructor with parameters 
 public ConstructorExample(int x, int y) {
num1 = x;
num2 = y;
System.out.println("sum of two numbers is " + (x+y));
}

public ConstructorExample(String fname, String lname) {
firstName = fname;
lastName = lname;
System.out.println("name is "+ fname+ " "+lname);
}

/**
 * @param args
 */
public static void main(String[] args) {

// Calls the default constructor.
ConstructorExample constructorExample = new  
                                ConstructorExample();
ConstructorExample constructorExample1 = new 
                                ConstructorExample(10, 20);
ConstructorExample constructorExample2 = new 
                                ConstructorExample("java", "tutorial");
}
}

Output:
Default constructor
sum of two numbers is 30
name is java tutorial

**************************************************************
public class ConstructorDemo extends ConstructorExample {

int x;
int y;
String fname;
String lname;


  public ConstructorDemo() {
super();//Calls the super class constructor
System.out.println("default constructor for sub class");
}

public ConstructorDemo(int x, int y) {

/*Here if we did not specify the super keyword for 2 argument constructor, it will implicitly call the no argument constructor of super class. Hence we should specify the super with proper arguments in order to call the super class argument constructors.*/
 
super(x, y);
this.x = x;
this.y = y;
System.out.println("Sum of two numbers in sub class" + (x + y));
}

public ConstructorDemo(String fname, String lname) {
super(fname, lname);
this.fname = fname;
this.lname = lname;
System.out.println("name in sub class is " + fname + " " + lname);
}

/**
 * @param args
 */
public static void main(String[] args) {

   // First it calls the default construcotr of super class as we have
  // specified super in default constructor
  ConstructorDemo constructorDemo = new ConstructorDemo();
   ConstructorDemo constructorDemo1 = new ConstructorDemo(100, 200);
  ConstructorDemo constructorDemo3 = new 
                                 ConstructorDemo("constructor", "example");
}

}
Output:
Default constructor
default constructor for sub class
sum of two numbers is 300
Sum of two numbers in sub class300
name is constructor example
name in sub class is constructor example

No comments:

Post a Comment