Login    New User    Forgot Password    Help      

Overloading Constructors

GO TO INDEX

Overloading Constructors

Constructors are used to assign initial values to instance variables of the class. A default constructor with no arguments will be called automatically by the Java Virtual Machine (JVM). Constructor is always called by new operator. Constructor are declared just like as we declare methods, except that the constructor don't have any return type. Constructor can be overloaded provided they should have different arguments because JVM differentiates constructors on the basis of arguments passed in the constructor.

Whenever we assign the name of the method same as  class name. Remember this method should not have any return type. This is called as constructor overloading

We have made one program on a constructor overloading, after going through it the concept of constructor overloading will get more clear. In the example below we have made three overloaded constructors each having different arguments  types so that the JVM can differentiates between the various constructors.

Example

class abc
{
int a;
int b;
        
 abc()
        {
        System.out.println("No argument are passed");
        a=10;
        b=20;
        }
       
 abc(int i)
        {
        System.out.println("only one argument is passed");
        a=i;
        b=i;
        }
       
 abc(int i ,int j)
        {
        System.out.println("Both arguments are passed");
        a=i;
        b=j;
        }

        void showdata()
        {
        System.out.println("Value of a is "+a);
        System.out.println("Value of b is "+b);
        }
}
class ol2
{
public static void main(String args[])
{
abc ob1 = new abc();
ob1.showdata();
abc ob2 = new abc(10);
ob2.showdata();
abc ob3 = new abc(20,30);
ob3.showdata();
}
}

Output



Java Tutorials