1 Attachment(s)
Does a method location matters?
Hi Mentors,
I was going through parametrized constructors, and i am facing an issue with the location of the method definition.
Please have a look at the code as below:-
Code:
class Box
{
double width;
double height;
double depth;
// Defining the parametrized constructors
Box(double w, double h, double d)
{
if(w > 0)
{
width = w;
}
else
{
width = 1.0;
}
if(h > 0)
{
height=h;
}
else
{
height = 1.0;
}
if(d > 0)
{
depth = d;
}
else
depth = 1.0;
//Calculates and return the volume to the calling routines
double getVol()
{
return depth*height*width;
}
}
}
class BoxDemo7
{
public static void main(String[] args)
{
Box mbox1 = new Box(3,4,5);
Box mbox2 = new Box(2,3,4);
System.out.println("Volume for 1st Box is:=" + mbox1.getVol());
System.out.println("Volume for 2nd Box is:=" + mbox2.getVol());
}
}
The error the javac compiler giving me is as below:-
Attachment 2419
But when i change the location of the getVol() function i.e above my parametrized constructor the code works fine for me.
Please suggest the needful.
Thanks in advance
Ankit Gupta
Re: Does a method location matters?
Double check the bracket locations in your code....as posted, the getVol method is within the Box constructor
Re: Does a method location matters?
Hi doWhile,
Thanks a lot for the information, have made the necessary changes i.e moved the method out of the constructor body, now the code works fine.
Thanks.
Ankit