Objects and Classes
Create an object
Create
How to create an object
- To create an object, you use the new keyword to create a new instance of a class.
- Each time the new keyword creates an object, Java calls the constructor for the object, which initializes the instance variables for the object.
- After you create an object, you assign it to a variable. When you do, a reference to the object is stored in the variable. Then, you can use the variable to refer to the object.
- To send arguments to the constructor, code the arguments within the parentheses that follow the class name, separated by commas.
- The arguments you send must be in the sequence and have the data types called for by the constructor.
How to create an object in two statements
ClassName variableName; variableName = new ClassName(argumentList);
Example with no arguments
Product product; product = new Product();
How to create an object in one statement
ClassName variableName = new ClassName(argumentList);
Example 1: No arguments
Product product = new Product();
Example 2: One literal argument
Product product = new Product("java");
Example 3: One variable argument
Product product = new Product(productCode);
Example 4: Three arguments
Product product = new Product(code, description, price);