0

I'm trying to write a Time object that has an increment method adding arbitrary seconds to it, so here is the code :

class Time {
int hour, minute;
double second;

public Time(int hour, int minute, double second) {
    this.hour = hour;
    this.minute = minute;
    this.second = second;
}

public Time(double seconds) {
    this.hour = (int) (seconds/3600);
    seconds -= this.hour*3600;
    if (this.hour >= 24) this.hour -= 24;
    this.minute = (int) (seconds/60);
    seconds -= this.minute*60;
    this.second = seconds;
}

public static double convertToSeconds(Time t) {
    double seconds = t.hour*3600 + t.minute*60 + t.second;
    return seconds;
}

public static void increment(Time t, double s) {
    double seconds = convertToSeconds(t) + s;
    t = new Time(seconds);
    printTime(t);
}

public static void printTime(Time t) {
    System.out.println(t.hour + ":" + t.minute + ":" + t.second);
}

public static void main(String[] args) {
    Time t = new Time(11, 8, 3.0);
    printTime(t);
    increment(t, 60);
    printTime(t);
}
}

It gives this output :

11:8:3.0
11:9:3.0
11:8:3.0

It shows the object has been changed as expected inside the increment method, but back in main after the invocation of the increment method, the object remains the same. What's the problem with it?

Joseph Tesfaye
  • 814
  • 14
  • 26

2 Answers2

0

You can not change the reference contents of a variable through method parameters, i.e. t = new Time(seconds); does not change the address where the main methods has pointed t at. If you want to change it persistently, you have to return t in increment and change main to

t = increment(t, 60);
printTime(t);
Smutje
  • 17,733
  • 4
  • 24
  • 41
  • Thanks Smutje! I know the return type method, but now I want to write a modifier/void method that modifies the object directly. Do you have any other idea if as you said the reference cannot be changed through method parameters? – Joseph Tesfaye Oct 22 '15 at 08:09
  • @IvanH.Jc you could add `t = new Time(seconds); this.hours = t.hours; this.minutes = t.minutes; this.seconds = t.seconds;`. But in general using immutable objects is good practice. – assylias Oct 22 '15 at 08:14
  • @assylias Thanks! That's exactly what I've just done, haha. – Joseph Tesfaye Oct 22 '15 at 08:18
0

You are setting t to point to a new object inside your method. This only changes the refrernce of t inside your method and has no affect on the outer scope.

To fix, either change your method to return the nee object (and assign it in your main) or change your implementation to change the time in the existing object rather than creating a new one.

Nir Levy
  • 12,750
  • 3
  • 21
  • 38