gpt4 book ai didi

java - 不可变类的静态与非静态方法

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:11:33 25 4
gpt4 key购买 nike

给出下面的类定义。如何决定 stub 方法应该是静态的还是非静态的?

class Point {
private final int x;
private final int y;

public Point(int x, int y) {
this.x = x;
this.y = y;
}

// Should the methods add(), subtract() and inverseOf() be non-static ...

public Point add(Point point) {

}

public Point subtract(Point point) {

}

public Point inverseOf() {

}


// Or static?

public static Point add(Point point1, Point point2) {

}

public static Point subtract(Point point1, Point point2) {

}

public static Point inverseOf(Point point) {

}
}

最佳答案

我会去举例方法。然后,您可以将这些方法作为接口(interface)的一部分并覆盖它们。当您必须处理 2d 点或 3d 点并且有一些并不真正关心并且只需要对实现接口(interface)的 Points 执行操作的客户端代码时,您将获得好处。

关于java - 不可变类的静态与非静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2177685/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com