繁体   English   中英

您如何在Java方法中使用构造函数参数?

[英]How do you use a constructors parameter in a method in Java?

public class GPSping {

    private double pingLat;
    private double pingLon;
    private int pingTime;

    public GPSping(double Lat, double Lon, int Time)
    {
       pingLat = Lat;
       pingLon = Lon;
       pingTime = Time
    }

    public int timeTo(GPSping anotherPing)

使用上面的确切方法签名(timeTo),如何创建辅助GPSping?

我的目标是创建一种计算两次ping之间的时间的方法。

您只需调用getPingTime方法即可,该方法返回另一个对象的pingTime。 这意味着您需要在GPSping对象中使用getPingTime方法。

public int getPingTime(){
 return pingTime;
}

然后您的timeTo方法看起来像这样

public int timeTo(GPSping anotherPing){
 return getPingTime()-anotherPing.getPingTime();
}

假设您有每个变量的getter / setter,可以做到这一点

public int timeTo(GPSping anotherPing) {
   return anotherPing.getPingTime() - this.pingTime; // If you want just 
   // magnitude use Math.abs()
}

你的吸气剂应该是这样的

public int getPingTime() {
 return pingTime;
}

有关获取器/设置器的更多信息

你可以在这里使用龙目岛

实际上,可以使用注释(@ Getter,@ Setter,@ AllArgsConstructor)来代替手动创建

使用这些注释,无需手动实现mutator和accessor方法。 尽管大多数IDE允许您生成这些方法,但使用Lombok可使您的类看起来更整洁,尤其是当字段列表很长时

@Getter
@Setter
@AllArgsConstructor
public class GPSping {

    private double pingLat;
    private double pingLon;
    private int pingTime;

public int timeTo(GPSping newPing){
 return getPingTime()-newPing.getPingTime();
}

}

实际上,您不需要其他的setter或getter。 这是一类,您可以直接访问其属性:

public class GPSping {

    private final int pingTime;
    private final double pingLat;
    private final double pingLon;

    public GPSping(int pingTime, double pingLat, double pingLon) {
        this.pingTime = pingTime;
        this.pingLat = pingLat;
        this.pingLon = pingLon;
    }

    public int timeTo(GPSping anotherPing) {
        return Math.abs(pingTime - anotherPing.pingTime);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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