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

Popular posts from this blog

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.

Program to input age from user and throw user-defined exception if entered age is negative