0

Here is a code with no param constructor

public class misc2 {


    misc2(String x){

    }

    public static void main(String ... args){

        misc2 m = new misc2();  // this throws a compilation error

    }
}

My question is why does it throw a compilation error, when Java automatically creates a default constructor, in this case misc2(){...}. if it is not defined already.

Also, now if I add a no param constructor misc2(){...}, which one is actually called by the JVM. Is it the default param or the no param. The second question is because if Java already creates a default constructor with no parameters already, the what is the need to explicitly create a constructor in some cases in the Java program?

1 Answers1

1

Java creates a default constructor if and only if no other explicit constructor is provided.

From the docs:

You don't have to provide any constructors for your class, but you must be careful when doing this. The compiler automatically provides a no-argument, default constructor for any class without constructors.

See: https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html

Kon
  • 10,702
  • 6
  • 41
  • 58
  • Okay, also, since Java creates a default constructor IFF there is none defined, then why does the one defined with params throw an error, because then, as per the code, in this case we havent defined any constructor, so Java needs to create a default itrelf and not throw an error. I mean default and parameterized are totally separate. Then why the behaviour? – Bishwaroop Chakraborty Jul 20 '16 at 17:54
  • @BishwaroopChakraborty Your error comes because you are trying to construct the class using no-arguments. `new misc2()` has no arguments, but since you've defined a constructor which takes a `String`, you have to use that. Something like `new misc2("hello")` will work. You can also define your own no-argument constructor if you want. – Kon Jul 20 '16 at 17:55