簡體   English   中英

如何在 Java 中調用替代的 static 構造函數?

[英]How do you invoke an alternative static constructor in Java?

您如何在 Java 中調用這些替代 static 構造函數?

我想使用 newFromLatLong 格式創建一個 Location object 但不知道如何

public class Location {

    public final double x;
    public final double y;

    public Location(double x, double y) {
        this.x = x;
        this.y = y;
    }

    public static Location newFromPoint(Point point, Location origin,
            double scale) {
        return new Location(point.x / scale + origin.x, origin.y - point.y
                / scale);
    }

    
    public static Location newFromLatLon(double lat, double lon) {
        double y = (lat - CENTRE_LAT) * SCALE_LAT;
        double x = (lon - CENTRE_LON)
                * (SCALE_LAT * Math.cos((lat - CENTRE_LAT) * DEG_TO_RAD));
        return new Location(x, y);
    }

您有 static 方法來創建 object,因此您可以在 class 本身上調用它們,這將返回一個Location ZA8CFDE6331BD4B6266AC9。 您可以將其用於進一步用途。

Location location = Location.newFromLatLon(1.1, 1.2);

考慮使用構建器模式來創建您的位置 object。 為避免重復代碼,我建議使用 Lombok @Builder注解:

https://projectlombok.org/features/Builder

此外,考慮您使用相同的Location object 作為newFromPoint方法的參數:


public static Location newFromPoint(Point point, Location origin,
            double scale) {
        return new Location(point.x / scale + origin.x, origin.y - point.y
                / scale);
}

也許您需要查看您的域定義。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM