简体   繁体   中英

How do you invoke an alternative static constructor in Java?

How do you call these alternative static constructors in Java?

I want to create a Location object using the newFromLatLong format and do not know how to

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

You have static methods to create an object, so you call them on the class itself, which will return you a Location object. You can use it for further uses.

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

Consider use a builder pattern to create your Location object. To avoid duplicate code, I recommend to use Lombok @Builder annotation:

https://projectlombok.org/features/Builder

Also, consider you are using the same Location object as parameter for the newFromPoint method:


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

Maybe you will need to take a look to your domain definition.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM