Search code examples
javaclassnew-operatorinstantiation

Is it the constructor of a class that follows the new keyword in java?


when we write something like

Scanner scanner = new Scanner(System.in);

Do we actually call the constructor defined in Scanner class with new Scanner(System.in)? If the answer is yes then how is it possible to access the constructor which is a special type of method without creating an instance. If the answer is no then why does it always have to have a name of a constructor?


Solution

  • Do we actually call the constructor defined in Scanner class with new Scanner(System.in)?

    yes.

    If the answer is yes then how is it possible to access the constructor which is a special type of method without creating an instance.

    You can copy the bytecode and create a method with the same code to do the same thing. However, you can't call the constructor by normal means as a method.

    A Constructor is like a Method in some ways, however it is different in the sense it is only called to initialise a new object and is not used to be called directly.