Java Reference
In-Depth Information
Parameterized Constructors
In the preceding example, a parameter-less constructor was used. Although this is fine for
some situations, most often you will need a constructor that accepts one or more paramet-
ers. Parameters are added to a constructor in the same way that they are added to a method:
just declare them inside the parentheses after the constructor's name. For example, here,
MyClass is given a parameterized constructor:
The output from this program is shown here:
In this version of the program, the MyClass( ) constructor defines one parameter called
i , which is used to initialize the instance variable, x . Thus, when the line
executes, the value 10 is passed to i , which is then assigned to x .
Search WWH ::




Custom Search