Skip to content
Advertisement

Define Methods in Interface Without Specifying Number of Parameters

I’m trying to implement classes from the same interface but with a different number of parameters in method like the code below.

interface Shape {
    double getArea();
}

class Square implements Shape {
    @Override
    public double getArea(double side) { // error because different number of parameter
        return side;
    }
}

class Triangle implements Shape {
    @Override
    public double getArea(double height, double width) { // error because different number of parameter
        return height * width / 2;
    }
}

Is there a way in Java to define methods in the interface without constraining the number of parameters?

Advertisement

Answer

You could use the ellipsis syntax (...) and then check the number of arguments passed to the method in runtime:

interface Shape {
    double getArea(double... args);
}

class Triangle implements Shape {
    @Override
    public double getArea(double args...) {
        if (args.length != 2) {
             throw new IllegalArgumentExeption
                       ("A triangle should have a height and a width");
        }
        double height = args[0];
        double width = args[1];
        return height * width / 2;
    }
}

But this completely misses the point of having an interface and implementing its methods.

The idiomatic way to handle this in Java would be to have each shape take the appropriate arguments in its constructor and implement a no-argument getArea() method that relies on its data members:

interface Shape {
    double getArea();
}

class Triangle implements Shape {
    private height;
    private width;

    public Triangle(double height, double width) {
        this.height = height;
        this.width = width;
    }

    @Override
    public double getArea() {
        return height * width / 2;
    }
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement