Java Reference
In-Depth Information
Display 5.3 Another Class with a main Added (part 2 of 2)
37
public static double toCelsius( double degreesF)
38
{
39
40
return 5*(degreesF - 32)/9;
41
}
Because this is in the definition of the
class Temperature , this is equivalent to
Temperature.toCelsius(degreesF) .
42
public static void main(String[] args)
43
{
44
double degreesF, degreesC;
45
46
Scanner keyboard = new Scanner(System.in);
47
System.out.println("Enter degrees Fahrenheit:");
48
degreesF = keyboard.nextDouble();
49
50
degreesC = toCelsius(degreesF);
51
52
Temperature temperatureObject = new Temperature(degreesC);
53
System.out.println("Equivalent Celsius temperature is "
54
+ temperatureObject.toString());
Because main is a static method, toString must have a
specified calling object like temperatureObject .
55
}
56
}
Sample Dialogue
Enter degrees Fahrenheit:
212
Equivalent Celsius temperature is 100.0 C
Self-Test Exercises
1. Is the following legal? The class RoundStuff is defined in Display 5.1.
RoundStuff roundObject = new RoundStuff();
System.out.println(“A circle of radius 5.5 has area”
+ roundObject.area(5.5);
2. In Display 5.1, we did not define any constructors for the class RoundStuff . Is this
poor programming style?
3. Can a class contain both static and nonstatic (that is, regular) methods?
4. Can you invoke a nonstatic method within a static method?
5. Can you invoke a static method within a nonstatic method?
6. Can you reference an instance variable within a static method? Why or why not?
 
Search WWH ::




Custom Search