Constructor Overloading in Java

Advertisements

Java Constructor Overloading

More than one constructor with different signature in a class is called constructor overloading. Signature of constructor includes:

  • Number of arguments
  • Type of arguments
  • Sequence of arguments

When we create an object, the compiler determines the most appropriate definition to use by comparing the signature of constructor with the instantiation of object.

Example of java constructor overloading


    //Student.java

    class Student
    {
        int Roll;
        String Name;
        double Marks;

        Student(int R,String N,double M)        // Constructor 1
        {
            Roll = R;
            Name = N;
            Marks = M;
        }

        Student(String N,double M,int R)        // Constructor 2
        {
            Roll = R;
            Name = N;
            Marks = M;
        }

        void Display()
        {
            System.out.print("\n\t" + Roll+"\t" + Name+"\t" + Marks);
        }
    }

    class ConstructorOverloadingDemo
    {
        public static void main(String[] args)
        {
            Student S1 = new Student(1,"Kumar",78.53);  // Statement 2
            Student S2 = new Student("Sumit",89.42,2);  // Statement 1

            System.out.print("\n\tRoll\tName\tMarks\n");
            S1.Display();
            S2.Display();
        }
    }

    Output:
                Roll    Name    Marks

                1       Kumar   78.53
                2       Sumit   89.42

In the above example, we have two constructors.

Statement 2 will invoke constructor 1 b'coz the signature of constructor 1 is similar to the statement 2.

Statement 1 will invoke constructor 2 b'coz the signature of constructor 2 is similar to the statement 1.

Advertisement