Java Calling a constructor from another constructor without immediately having parameters

Is there a way to call a constructor from another constructor without immediately having parameters for it?

I ran into this problem when trying to create a constructor for my class SimpleDate, which took a time parameter in milliseconds and used a different constructor to create the class (code below). The problem I ran into was that the constructor call should be on the first line, but I really don't see to get the instance Calendarwith the right time without first setting the time in milliseconds on the previous line. I don’t see how this is done on one line, because it setTimeInMillisis the void method, and I don’t think that it is possible to return the value after the method is called (if this is the way I would like to know how Well). I understand that all this is not absolutely necessary, but I want to know if this is possible, and if so, how I will do it.

        public SimpleDate(long timeMillis) {
            this(Calendar.getInstance().setTimeInMillis(timeMillis));//Obviously this doesn't work because setTimeInMillis is a void method
        }

        public SimpleDate(Calendar calendar) {
            this.year = calendar.get(Calendar.YEAR);
            this.month = calendar.get(Calendar.MONTH) + 1;
            this.day = calendar.get(Calendar.DAY_OF_MONTH);

            this.hour = calendar.get(Calendar.HOUR_OF_DAY);
            this.minute = calendar.get(Calendar.MINUTE);
            this.second = calendar.get(Calendar.SECOND);
        }
+4
source
2

, , .

protected static Calendar getCalendarForMillis(long millis) {
    Calender ret = Calendar.getInstance();
    ret.setTimeInMillis(millis);
    return ret;
}

public SimpleDate(long millis) {
    this(getCalendarForMillis(millis));
}

- : , . .

+2

, , - , Calendar, long millis Calendar.

Calendaryour fields , , . , millisCalendar, , , - .

, , - Calendaryour fields , :

public SimpleDate(Calendar calendar) {
  setDateFields(calendar);        
}

public SimpleDate(long millis) {
  Calendar calendar = Calendar.getInstance();
  calendar.setTimeInMillis(millis);
  setDateFields(calendar);      
}

private void setDateFields(Calendar calendar) {
  this.year = calendar.get(Calendar.YEAR);
  this.month = calendar.get(Calendar.MONTH);
  this.day = calendar.get(Calendar.DAY_OF_MONTH);
  this.hour = calendar.get(Calendar.HOUR_OF_DAY);
  this.minute = calendar.get(Calendar.MINUTE);
  this.second = calendar.get(Calendar.SECOND);
}

, - , , , , , .

+1

All Articles