Section 4.5 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
Subsection 4.5.1
You can watch this video or read through the content below it.
Subsection 4.5.2 Programmer-Defined Classes
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.
The following Java code declares and instantiates a variable that will represent a Widget.
Subsection 4.5.3 SG1: Declare variable of appropriate class datatype.
Widget alpha;
Subsection 4.5.4 SG2: Assign to variable: keyword new, followed by class name, followed by ().
alpha = new Widget();
Subsection 4.5.5 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);
Answer.
So the final code looks like this:
Widget alpha;
alpha = new Widget();
alpha = new Widget(42);
Practice Pages.
You have attempted of activities on this page.