Below code shows error at line 4
class MyClass{
public MyClass(int a){ } //Line 2
public static void main(String a[]){
MyClass n = new MyClass(); //Line 4
System.out.print("TRUE");
}
}
But, once i remove line 2, it runs without any error. Although, I didn’t add default constructor. Why ?
Remember that
Compilerprovides your class with adefault constructoronly if you have not given any explicit constructor. As soon as you declare your own constructor, parameterized or 0-arg, the compiler won’t give you the default constructor.Now in your code, you have declared a parameterized constructor, compiler won’t give a default one. So, you actually don’t have any 0-arg constructor, and hence you cannot use it.
Of course if you remove your line 2, then you haven’t declared any explicit constructor, in which case Compiler adds a default 0-arg constructor, and hence your code succeeds. Also note that the default constructor is the one give by compiler. When you declare your 0-arg constructor, it’s not called a default one, but just a 0-arg constructor.
So, whenever you are declaring a parameterized constructor, make sure that you also declare a
0-arg constructorexplicitly, if of course you are using it.