Creating New Objects: Constructors
You call a constructor to create a new object. A constructor is a special kind of method that you write as part of a class. It looks like an ordinary method, but a constructor magically allocates memory for a new instance of an object, then executes the statements that you write in the constructor body. Your statements typically initialize the fields of the new object.
Like any method, a constructor needs to be given a name. A constructor also needs to indicate that its return type is “an object of the class that this constructor belongs to”. The Java design team chose to roll these two needs together, by adopting the conventions that:
-
A constructor has the same name as the class it belongs to.
-
A constructor ...
Get Just Java™ 2 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.