The pointless ocean moans on top of each conventional mathematics.

In case if you haven’t defined any constructor for a class, by default Java compiler would call the default Constructor.

 

In case if you want to add your own Constructor for a Class, you can do so as shown below.

 

Please note, when you define your own constructor then the compiler wouldn’t call/add the default constructor.

 

Consider the following program –  JConstrutor.java

public class JConstructor {

         public JConstructor() {

                System.out.println(“Constructor called”);

        }

        public static void main(String[] args) {

                JConstructor j = new JConstructor();

        }

 }

OUTPUT

Constructor called

 

You can add any number of constructors with different argument types.

public class JConstructor {

         public JConstructor(int a) {

               System.out.println(“Parameterized Constructor called”);

        }

         public static void main(String[] args) {

                 JConstructor j = new JConstructor(10);

        }

 }

OUTPUT

Parameterized Constructor called

 

When you define a Constructor of the form classname(int a){ }, while creating an object of that class, you have to specify the argument appropriately.

Eg:- classname objname=new classname(10);

 

You are likely to see a compilation error, in case if there is a mismatch in the argument type/number of arguments passed.

 Consider the following code.

 

public class JConstructor {

         public JConstructor() {

                System.out.println(“Constructor called”);

        }

         public static void main(String[] args) {

                JConstructor j = new JConstructor(10);

        }

}

Exception in thread “main” java.lang.Error: Unresolved compilation problem:

        The constructor JConstructor(int) is undefined

         at JConstructor.main(JConstructor.java:11)

 

 The following code is an example of argument type mismatch.

 

public class JConstructor {

         public JConstructor(String str) {

                System.out.println(“Parameterized Constructor called”);

        }

       public static void main(String[] args) {

                JConstructor j = new JConstructor(10);

        }

 }

OUTPUT

Exception in thread “main” java.lang.Error: Unresolved compilation problem:

        The constructor JConstructor(int) is undefined

         at JConstructor.main(JConstructor.java:11)