+ 1

Why we need to put the "()" at the end of a declaration of an instance?

Example: Person p1 = new Person(); And what's its purpose?

20th Apr 2019, 12:24 AM
Kevin Pan
1 Answer
+ 1
In Java, the "new" keyword is used to call a class's constructor method. You can define a constructor method for a class by naming the method with the same identifier as the class. Example: class Number { int value; Number(int x) { //the constructor method value = x; } } In this example, the constructor needs an integer argument, so I would call it like this: Number x = new Number(42); However, in Java, if you don't write the constructor for a class it is given a default constructor which initializes all of the fields to their default value (Ex: an int would be initialized to 0; a String would be initialized to null). However, it is important to remember that this default constructor, although it accepts zero arguments, is still a method. Since it's a method, it must be called with parenthesis.
20th Apr 2019, 1:31 AM
Jack McCarthy
Jack McCarthy - avatar