Friday, 25 November 2016

Program for Constructor Overloading

Constructor is a special type of method which enables to initialize an object when it is first created. It has the same name as the class name in which it is declared. It does not specify a return type not even void. It has following syntax:
// Default constructor
<class-name> ( ) {
    // Statements
}

OR

// Parameterized constructor
<class-name> (parameter list) {
    // Statements
}

Like methods, constructors can also be overloaded. Constructor overloading is way of having more than one constructor which does different tasks. For e.g. Vector class has 4 types of constructors. If you do not want to specify the initial capacity and capacity increment then you can simply use default constructor of Vector class like this
Vector v = new Vector( ); 

PROGRAM
class ConstructorOverloading {

 int a,b; // data members declaration
 ConstructorOverloading() // default constructor initialized to zero
 {
  a = b = 0;
 }
 
 ConstructorOverloading(int x,int y) // parameterized constructor
 {
  a = x;
  b = y;
 }
 
 void display() // method to display the value of variables
 {
  System.out.println("a = "+a+" b = "+b);
 }
 
 public static void main(String args[]) // main method
 {
  ConstructorOverloading s1 = new ConstructorOverloading();  // call default constructor
  ConstructorOverloading s2 = new ConstructorOverloading(10,20);  // call parameterized constructor
  s1.display();
  s2.display();
 }
}
OUTPUT
C:\>javac ConstructorOverloading.java
C:\>java ConstructorOverloading
a = 0 b = 0
a = 10 b = 20

No comments:

Post a Comment