Java Reference
In-Depth Information
The getter methods for these data fields
are provided in the class, but omitted in the
UML diagram for brevity.
BMI
-name: String
-age: int
-weight: double
-height: double
The name of the person.
The age of the person.
The weight of the person in pounds.
The height of the person in inches.
Creates a BMI object with the specified
name, age, weight, and height.
Creates a BMI object with the specified
name, weight, height, and a default age 20.
Returns the BMI.
Returns the BMI status (e.g., normal,
overweight, etc.).
+BMI(name: String, age: int, weight:
double, height: double)
+BMI(name: String, weight: double,
height: double)
+getBMI(): double
+getStatus(): String
F IGURE 10.3
The BMI class encapsulates BMI information.
Assume that the BMI class is available. Listing 10.3 gives a test program that uses this class.
L ISTING 10.3
UseBMIClass.java
1 public class UseBMIClass {
2 public static void main(String[] args) {
3 BMI bmi1 = new BMI( "Kim Yang" , 18 , 145 , 70 );
4 System.out.println( "The BMI for " + bmi1.getName() + " is "
5 + bmi1.getBMI() + " " + bmi1.getStatus());
6
7 BMI bmi2 = new BMI( "Susan King" , 215 , 70 );
8 System.out.println( "The BMI for " + bmi2.getName() + " is "
9 + bmi2.getBMI() + " " + bmi2.getStatus());
10 }
11 }
create an object
invoke instance method
create an object
invoke instance method
The BMI for Kim Yang is 20.81 Normal
The BMI for Susan King is 30.85 Obese
Line 3 creates the object bmi1 for Kim Yang and line 7 creates the object bmi2 for Susan
King . You can use the instance methods getName() , getBMI() , and getStatus() to
return the BMI information in a BMI object.
The BMI class can be implemented as in Listing 10.4.
L ISTING 10.4
BMI.java
1 public class BMI {
2
private String name;
3
private int age;
4
private double weight; // in pounds
5
private double height; // in inches
6
public static final double KILOGRAMS_PER_POUND = 0 . 45359237 ;
7
public static final double METERS_PER_INCH = 0 . 0254 ;
8
9
public BMI(String name, int age, double weight, double height) {
constructor
10
this .name = name;
 
 
Search WWH ::




Custom Search