Java Reference
In-Depth Information
asconvertingfromdegreesCelsiustodegreesFahrenheit).Youdon'twanttocreatean
objectfromthisclassinordertoperformaconversion.Instead,yousimplywanttocall
amethodandobtainitsresult. Listing2-11 addressesthisrequirement bypresentinga
Conversions classwithapairofclassmethods.Thesemethodscanbecalledwithout
having to create a Conversions object.
Listing 2-11. A Conversions utility class with a pair of class methods
class Conversions
{
static double c2f(double degrees)
{
return degrees*9.0/5.0+32;
}
static double f2c(double degrees)
{
return (degrees-32)*5.0/9.0;
}
}
Listing 2-11 's Conversions class declares c2f() and f2c() methods for con-
vertingfromdegreesCelsiustodegreesFahrenheitandviceversa,andreturningtheres-
ultsoftheseconversions.Each method header (methodsignatureandotherinformation)
is prefixed with keyword static to turn the method into a class method.
To execute a class method, you typically prefix its name with the class name. For
example,youcanexecute Conversions.c2f(100.0); tofindouttheFahrenheit
equivalentof100degreesCelsius,and Conversions.f2c(98.6); todiscoverthe
Celsiusequivalentofthenormalbodytemperature.Youdon'tneedtoinstantiate Con-
versions andthencallthesemethodsviathatinstance,althoughyoucoulddoso(but
that isn't good form).
Note Every application has at least one class method. Specifically, an application
mustspecify public static void main(String[] args) toserveasthe
application'sentrypoint.The static reservedwordmakesthismethodaclassmeth-
od. (I will explain reserved word public later in this chapter.)
Becauseclassmethodsarenotcalledwithahiddenargumentthatreferstothecurrent
object, c2f() , f2c() ,and main() cannotaccessanobject'sinstancefieldsorcallits
 
Search WWH ::




Custom Search