Java Reference
In-Depth Information
The statements in Lines 11, 12, and 13 output the values of x , y , and z , respectively, to
three decimal places. Note that the value of y in Line 12 is output to three decimal places.
Because the number stored in y has only two decimal places, a 0 is printed as the third
decimal place.
Packages and User-Defined Classes
Chapter 7 discusses user-defined methods, in particular methods with parameters. As
explained in Chapter 3, there are two types of variables in Java—primitive and reference.
The program in Example 7-8 illustrates that if a formal parameter is of the primitive type and
the corresponding actual parameter is a variable, then the formal parameter cannot change the
value of the actual parameter. Changing the value of a formal parameter of a primitive data type
has no effect on the actual parameter. However, if a formal parameter is a reference variable,
then both the actual and the formal parameter refer to the same object. That is, only formal
parameters that are reference variables are capable of passing values outside the function.
Java provides classes corresponding to each primitive data type, so that values of primitive
data types can be considered objects. For example, you can use the class Integer to
treat int values as objects, class Double to treat double values as objects, and so on.
These classes, called wrapper classes, were described in Chapter 6.
As noted in Chapter 7, Java does not provide any class that wraps primitive type values in
objects and, when passed as parameters, change their values. If a method returns only one
value of a primitive type, then you can write a value-returning method. However, if you
encounter a situation that requires you to write a method that needs to pass more than
one value of a primitive type, then you should design your own classes. In the next
section, we introduce various classes to accomplish this. For example, we design the
class IntClass so that values of the int type can be wrapped in an object. The class
IntClass also provides methods to change the value of an IntClass object. We use
reference variables of the IntClass type to pass int values outside a method.
Primitive Type Classes
This section presents the definitions of the class es IntClass , LongClass , CharClass ,
FloatClass , DoubleClass , and BooleanClass .
Class: IntClass
public class IntClass
{
private int x;
//variable to store the number
//default constructor
//Postcondition: x = 0
public IntClass()
{
x = 0;
}
 
 
Search WWH ::




Custom Search