2.3. Worked Example: Create Instance of Widget¶
Subgoals for using objects (creating instances)
Declare variable of appropriate class datatype.
Assign to variable: keyword new, followed by class name, followed by ().
Determine whether parameter(s) are appropriate (API)
Number of parameters
Data types of the parameters
You can watch this video or read through the content below it.
Widget is a made-up class for this lesson. As you become proficient in Java, you will write your own classes, as well. Luckily, the developers who defined the Widget class provided the following constructor documentation.
Unfortunately, because we do not have an implementation of the Widget class, the ActiveCode block below will not work with the Widget class. When you get to the end of this lesson, try to use the subgoals to reconstruct your work from the previous lesson on the Random object, without looking.
SG1: Declare variable of appropriate class datatype.
SG2: Assign to variable: keyword new, followed by class name, followed by ().
alpha = new Widget();
SG3: Determine whether parameter(s) are appropriate (API)
In the photo of the documentation above, we can specify any
int value for how many items we want in the widget object.
alpha = new Widget(42);