Hi all,
A question asks me to write overloading functions to square,circle ,rectangle and triangle....
But since the square and circle have only one parameter I had to change the parameter of area of circle to double......
Is this the only way to accomplish this.....
Are there any other ways of writing it with out this kind of cheating....

 public class ShapeArea{
    public static int Area(int sideLength){
        return Area(sideLength,sideLength);
        }
    public static int Area(int sideA,int sideB){
        return sideA*sideB;
        }
    public static double Area(double r){
             return Math.PI*r*r;
        }
    public static void main(String cmd[]){
        System.out.println(Area(5.0));
    }
}

Please suggest me towards a good decision....
Thanks in advance!

Recommended Answers

All 2 Replies

The original question seems flawed. As you say, square and circle each require one numeric parameter, triangles and rectangles both need two, so there's no way to distinguish those method signatures without resorting to highly artifical solutions like the one you show.
Are you certain that you were not asked for a polymorphic solution? Polymorphism would make perfect sense here, but overloading doesn't.

also: whoever asked you this, either wasn't talking about java, or doesn't know what (s)he's talking about. In java, there are no functions, just methods.
besides, just because you pass a parameter, doesn't mean you have to use it (ok, it's not logical to pass a parameter you don't use, but hey...)
you could, for example, pass a Color value in which you 'paint' your object.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.