开发者

Passing a method call to a constructor,java

开发者 https://www.devze.com 2023-04-08 22:16 出处:网络
Assignment: Time class: give it 3 private data members for hour, minute, and second. Use type long or int.

Assignment: Time class:

give it 3 private data members for hour, minute, and second. Use type long or int.

If you use int you must cast inside the ctors.

add a no-arg ctor that uses code like that in Listing 2.6 on p38 to assign values to hour, minute, and second from the current time.

add another ctor that will take a single long parameter named elapseTime (better would be elapsedTime), a number for milliseconds since the Unix epoch date. this second ctor will also use code as per Listing 2.6 to set the data members for that elapsed time since the epoch.

add a getter for each data member. Each getter will require only a single statement.

Getters are needed because the data members are private.

add a toString method that returns the hours, minutes, and seconds for a Time object.

here is my class Time() code, my setTime() code represents the book reference mentioned above.

package chapter_10;

public class Time {
    private long hour;
    private long minute;
    private long second;

    public Time() {

    }
    public void setTime(long elapsedTime){
       long millisecond = System.currentTimeMillis();
       second = millisecond / 1000;
       minute = second / 60;
       hour = minute /60;
       //equate for current time.
       second = second %60;
       minute = minute %60;
       hour = hour %24;
    }

    public long getHour() {
        return hour;
    }

    public long getMinute() {
        return minute;
    }

   开发者_如何学C public long getSecond() {
        return second;
    }

    public  String toString(){
       return getHour() + ":" + getMinute() + ":" + getSecond();
   }
}


public Time() {
    setTime(0L);
}

Calling an overridable method inside a constructor is bad practice, though. You should thus make the method private or final, or make the class itself final.

Also, your method is a bit strange, because it takes a time as argument, but doesn't do anything with it.


First of all, why would you want to call a class constructor from within a method of the same class?
The thing is that if you are accessing the class, you should have called a constructor before, unless your method is static, so for example, you could do this:

public static void setTime(long elapsedTime){
     ...
     new Time(elapsedTime);
     ...
}

Then from the invocation part:

Time.setTime(1L);

Although I think this could answer your question (if I understood correctly), the real question is why call a constructor of the same class from a method? Wouldn't it be better to just call the constructor and put all the logic of the method into it?

I hope this helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消