L0n35
L0n35

Reputation: 105

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)

Using this exact method signature above (timeTo) how do I create a secondary GPSping?

My goal is to create a method that calculates the time between two pings.

Upvotes: 1

Views: 78

Answers (4)

Tofu
Tofu

Reputation: 3613

You would simply call the getPingTime method which returns pingTime of the other object. Which means you need a getPingTime method in your GPSping object.

public int getPingTime(){
 return pingTime;
}

Then your timeTo method can look like such

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

Upvotes: 2

Oleg Cherednik
Oleg Cherednik

Reputation: 18245

Actually you do not need additional setters or getters. This is one class and you're able to access it's properties directly:

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

Upvotes: 0

Dulaj Kulathunga
Dulaj Kulathunga

Reputation: 1250

You can use lombok here

Actually , instead of manually creating , you can use annotation (@Getter,@Setter,@AllArgsConstructor)

Using these annotations remove the need to manually implements the mutator and accessor methods. Although most IDE allows you the generate these methods, using Lombok makes your classes look cleaner, especially when you have a long list of fields

@Getter
@Setter
@AllArgsConstructor
public class GPSping {

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

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

}

Upvotes: 0

Yoshikage Kira
Yoshikage Kira

Reputation: 1121

Assuming that you have getters/setters for each variable should can do this

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

Your getter should be like this

public int getPingTime() {
 return pingTime;
}

More about getters/setters

Upvotes: 1

Related Questions