在不指定参数数量的情况下在接口中定义方法

Define Methods in Interface Without Specifying Number of Parameters

我正在尝试从相同的接口实现 类,但在方法中使用不同数量的参数,如下面的代码。

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;
    }
}

Java有没有办法在不限制参数个数的情况下在接口中定义方法?

您可以使用省略号语法 (...),然后在运行时检查传递给该方法的参数数量:

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;
    }
}

但这完全忽略了拥有接口和实现其方法的要点。

在 Java 中处理此问题的惯用方法是让每个形状在其构造函数中采用适当的参数并实现依赖于其数据成员的无参数 getArea() 方法:

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;
    }
}

不幸的是,您无法实现接口的方法,然后将其参数(无论是否存在)更改为您喜欢的任何参数。

但幸运的是,有一种简单但非常有效的方法可以使用每个 class 的构造函数来解决您正在尝试做的事情,该构造函数将根据 class

这是一个小例子

interface Area {
    double getArea(); }


// a Triangle class that implements the Area interface
class Triangle implements Area {

    // Here as you see, each class has specific attributes, specific constructor arguments and for sure a specific method body
  
    double base,height;

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

    @Override
    public double getArea() {
        return ((double) 1/2) * base * height;
    }
}
//a Square class that implements the Area interface 
class Square implements Area {

    double length;

    Square(int length){
        this.length = length;
    }

    @Override
    public double getArea() {
        return length*length;
    }
}

public class Class {
    public static void main(String[] args) {

        //Creating a square object
        Square square = new Square(4);
        //Creating a triangle object
        Triangle triangle = new Triangle(12,3);

        System.out.println("Square's Area is :"+square.getArea()); // output : Square's Area is :16.0
        System.out.println("Triangle's Area is :"+triangle.getArea()); // output : Triangle's Area is :18.0

    }
}