The better way to implement volume( ) method in Box class is to compute the volume of the box and return the result to the method caller.
The following example is an improvised version to our previous program, with an enhancement in returning the volume result to the method caller:
Method returning volume will look like this:
public double volume( )
{
return width*height*depth;
}
Since the output of width*height*depth is of double type. We have mentioned double as return type i.e. double volume( ). Here we are returning the result as the calculated volume (i.e. width*height*depth).
Return result will be captured by a variable in 'ReturnCallingMethodDemo' class as shown below:
vol = box1.volume( );
Lets now do this on Eclipse IDE:
1. Launch Eclipse IDE, ensure that 'Third Project' Java project is available, modify the volume( ) method such that it returns a value as shown below -
3. Create two objects as instance of Box class as shown below:
6. Call the volume methods and store the returned result of volume( ) method of Box class into a variable and print as shown below:
You can also print the return value of volume( ) method directly as shown below:
System.out.println("The value of box1 is "+ box1.volume( ) );
Instead of:
double vol;
vol = box1.volume( );
System.out.println("The value of box1 is "+ vol);
Both scenarios work as same.
Download this project:
Click here to download the project containing 'ReturnMethodCallingDemo.java' file. (You can import the downloaded project into Eclipse ID on your system)
Please comment below to feedback or ask questions.
How does a method intake parameters will be explained with an example in the next post.
No comments:
Post a Comment