Creating Objects with new
Part of: Using Objects
The new Keyword To bring an object into existence you use the new operator, which calls a constructor . A constructor is a special method that builds and initializes a fresh object. Reading right to left in new Scanner(System.in): - new allocates memory for a new object. - Scanner(...) is the constructor call; the value in parentheses is an argument . - The resulting reference is stored in the variable sc. Anatomy of a Construction - The left side declares a variable of the object's type. - The right side instantiates (creates) the object. - The = stores the reference into the variable. The object produced is called an instance of the class. Creating it is called instantiation . Constructor Arguments Constructors often take arguments that set the object's initial state. Different argument lists call different constructors ( overloading ): The values you pass must match the types the constructor expects, in order. The String Shortcut String is special: because it is used so often, Java lets you create one with a literal in double quotes, with no new: This is the everyday way to make Strings. Most other classes still require new. Why Constructors Matter A constructor guarantees an ob
Challenge: Greeting Builder