Pass Data To A Constructor
The declaration of a constructor (or method) lets you know (“declares”) how many and what type of parameters will be passed to that constructor.
- It is important to note the different between parameters and arguments. Parameters refers to the list of variables in a method declaration; whereas, arguments are the values that are PASSED INTO the method when it is invoked. MEMORY TIP: To remember the different between the two, think that if you INVOKE someone (to make him mad), you may have an ARGUMENT with that person.
- The parameters and arguments must MATCH the method declaration’s parameters and data type and order.
- You can use pass any data type for a parameter to a constructor. If you want to pass a method into another method, then use a lambda expression or a method reference.
- When you don’t know how many arguments will be passed to a method, you can use the varargs construct to pass an arbitrary number of values to it. This is a shortcut instead of creating an array manually. To use a varargs, after the last parameter add an ellipse (…), a space and then the parameter name. This will allow the method to be invoked with any number of arguments. See https://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html/ for an example.
- A parameter name must be unique in its scope which means that it cannot have the same name as another parameter for the same method (or constructor) and it cannot be the name of a local variable INSIDE of the method (or constructor). However, a parameter can have the same name as one of the class’ fields. This is called SHADOWING in which the parameter cast “shadow” to the field. However, by convention, it is only use within constructors and methods that set a particular field.
- Arguments can be passed into a method (or constructor) in one of two ways:
- Primitive data types (e.g., int, double) are passed into a method by VALUE which means that any change to the parameter value exist only within the method scope. When the method is executed any change to the parameter is lost.
- Reference data types (e.g., array, object) are also passed into a method by VALUE but any change will persist when the method is invoked.