Java Reference
In-Depth Information
For example, the String class contains a class method called valueOf() , which can take
one of many different types of arguments (integers, Booleans, objects, and so on). The
valueOf() method then returns a new instance of String containing the string value of
the argument. This method doesn't operate directly on an existing instance of String ,
but getting a string from another object or data type is behavior that makes sense to
define in the String class.
Class methods also can be useful for gathering general methods together in one place.
For example, the Math class, defined in the java.lang package, contains a large set of
mathematical operations as class methods; there are no instances of the class Math , but
you still can use its methods with numeric or Boolean arguments.
For example, the class method Math.max() takes two arguments and returns the larger of
the two. You don't need to create a new instance of Math ; it can be called anywhere you
need it, as in the following:
int higherPrice = Math.max(firstPrice, secondPrice);
Dot notation is used to call a class method. As with class variables, you can use either an
instance of the class or the class itself on the left side of the dot. For the same reasons
noted in the discussion on class variables, however, using the name of the class makes
your code easier to read. The last two lines in this example produce the same result—the
string “550”:
String s, s2;
s = “item”;
s2 = s.valueOf(550);
s2 = String.valueOf(550);
References to Objects
As you work with objects, it's important to understand references.
A reference is an address that indicates where an object's variables and methods are
stored.
You aren't actually using objects when you assign an object to a variable or pass an
object to a method as an argument. You aren't even using copies of the objects. Instead,
you're using references to those objects.
To better illustrate the difference, Listing 3.4 shows how references work.
 
Search WWH ::




Custom Search