Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Example: Box Demo4 Example: Box Demo5

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 17

Example: Box demo4

Example: Box demo5


LTC: Example, Box demo4.
// Now, volume() returns the volume of a box.
class Box {
double width;
double height;
double depth;
Example: Box demo4-Cont…
// compute and return volume
double volume() {
return width * height * depth;
}
}
Example: Box demo4-Cont…
class BoxDemo4 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
Example: Box demo4-Cont…
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
Example: Box demo4-Cont…
/* assign different values to mybox2's
instance variables */
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
Example: Box demo4-Cont…
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}}
Example: Box demo4-Cont…
• The following is the output of BoxDemo4:
Volume is 3000.0
Volume is 162.0
Adding a method that takes parameters

• While some methods don’t need parameters,


most do.
• Parameters allow a method to be generalized.
• That is, a parameterized method can operate
on a variety of data and/or be used in a
number of slightly different situations.
LTC: Example, Box demo5
Adding a method that takes parameters
class Box {
double width;
double height;
double depth;
// compute and return volume
double volume() {
return width * height * depth;
}
Adding a method that takes parameters

// sets dimensions of box


void setDim(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
}
Adding a method that takes parameters

class BoxDemo5 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
Adding a method that takes parameters

// initialize each box


mybox1.setDim(10, 20, 15);
mybox2.setDim(3, 6, 9);
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
Adding a method that takes parameters

// get volume of second box


vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
Adding a method that takes parameters-
Cont...
The following is the output for BoxDemo5:
Volume is 3000.0
Volume is 162.0
Adding a method that takes parameters
• setDim( ) method is used to set the dimensions of each
box.
• For example, when
mybox1.setDim(10, 20, 15);
is executed,
10 is copied into parameter w,
20 is copied into h,
15 is copied into d.
The values of w, h, and d are then assigned to width,
height, and depth, respectively.
End of sessions

You might also like