2.3. Worked Example: Create Instance of Widget¶

Subgoals for using objects (creating instances)

  1. Declare variable of appropriate class datatype.

  2. Assign to variable: keyword new, followed by class name, followed by ().

  3. Determine whether parameter(s) are appropriate (API)

    1. Number of parameters

    2. Data types of the parameters

You can watch this video or read through the content below it.

Custom 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.

API docs for Widget constructor

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.

Widget alpha;

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);

Practice Pages

You have attempted of activities on this page