-1

We say in Java, that whenever we write a class and try to create an object for the same class, the compiler creates a default constructor of that class even though it has not been defined by the user. So suppose I have one class

class Constructor {
    public Constructor(int a, int b) {
    
    }
}
    
public class ConstructorLearn {
    public static void main(String ar[]){
        Constructor c = new Constructor();//Compile time error
    }
}

Now in the above class, I have not defined any constructor, but a parameterized constructor. Then why it is giving a compile-time error, because JVM should automatically create a default constructor when encountered new keyword.

Turing85
  • 18,217
  • 7
  • 33
  • 58
  • 1
    *"The default constructor is the no-argument constructor automatically generated unless you define another constructor."* - you defined another constructor => no default constructor for you. – luk2302 Jan 03 '22 at 19:07
  • 2
    *because JVM should automatically create a default constructor when encountered new keyword.* No. Constructors are not created when the JVM encounters `new` in the bytecode. Constructors are defined at compilation time. Not runtime. And you only get a default constructor if you define no other constructors. Nothing is particularly special about the default constructor. Just like `super` is the implicit first statement in your constructors (without `this`). – Elliott Frisch Jan 03 '22 at 19:12

2 Answers2

0

https://en.m.wikipedia.org/wiki/Default_constructor

In computer programming languages, the term default constructor can refer to a constructor that is automatically generated by the compiler in the absence of any programmer-defined constructors

Key wording is the absence of any other constructor.

Athanasios Kataras
  • 25,191
  • 4
  • 32
  • 61
0

You need declare a constructor empty and then the other constructor:

class Constructor {
  public Constructor() {

   }
  public Constructor(int a, int b) {

   }
}
noe
  • 11
  • 3